我创建了一个类,该类在构造函数中分配其自己的内存,并在析构函数中对其进行分配。但是,如果我将std::vector<CLASS> m(1)
其分配的数据作为std :: vector立即释放。这意味着我将丢失在构造函数中分配的所有数据。我该如何预防呢?例子:
#include <iostream>
#include <vector>
class test
{
public:
test()
{
std::cout<<"construction of test"<<std::endl;
std::cout<<" -MEMORY ALLOCATION"<<std::endl;
}
~test()
{
std::cout<<"destruction of test"<<std::endl;
std::cout<<" -MEMORY DEALLOCATION"<<std::endl;
}
};
int main()
{
std::vector<test> m(1);
std::cout<<"main"<<std::endl;
return 0;
}
该代码为我输出了此代码:
construction of test
-MEMORY ALLOCATION
destruction of test
-MEMORY DEALLOCATION
main
destruction of test
-MEMORY DEALLOCATION
我在Windows 7上使用带有-Os和-std = c ++ 11的g ++(如果很重要)。
发生的情况是test
创建了一个临时对象,将其复制到向量中,然后销毁。其副本将保留在向量中,直到向量被销毁为止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句