【发布时间】:2017-06-12 06:05:37
【问题描述】:
在我的赋值运算符方法中,我首先销毁对象管理的所有资源,然后进行分配,所以:
struct Animal
{
int aNumber;
int * buffer;
Animal() { buffer = new int[128]; }
Animal& operator= (Animal& other)
{
if (this != &other){
delete [] buffer;
//this->~Animal(); // I'm wondering if I can call this instead of deleting buffer here.
aNumber = other.aNumber;
}
~Animal() { delete[] buffer;}
};
我问这个问题的原因是,我不需要重写删除代码,而是可以将它放在一个地方。另外,我不认为调用析构函数会释放内存,所以当我在调用析构函数后分配aNumber时,我认为没关系。当我说内存没有被释放时,我的意思是,例如,如果我有一个vector<Animal>,并且vector 调用了vector[0] 的复制赋值运算符,vector[0] Animal 将调用它自己的析构函数,然后分配@987654327 @,但内存由向量管理(它没有被释放)。内存没有被释放是对的吗?
【问题讨论】:
-
只是不要[[[[
-
请更喜欢使用
std::vector<int>而不是动态分配内存。您将简化程序并减少内存管理的麻烦(std::vector为您管理内存)。
标签: c++ memory vector destructor