【发布时间】:2012-11-30 11:08:39
【问题描述】:
我想问几个关于正确销毁 int 指针和向量指针的问题。首先,我看到过去有人问过这类问题,几乎总是有几个回答说在 C++ 中使用向量指针、对象指针等不是很好的标准 C++ 编码实践,你应该实例化一个对象的副本。这可能是真的,但你并不总是能够控制在你到达之前已经奠定的范式。我需要使用的范例需要初始化指向几乎所有内容的指针。一种非常类似于 Java 的 C++ 方法。我们这样做的主要原因之一是我们的数据集太大,堆栈分配可能会溢出。
我的问题:
如果我有一个指向 int32_t 数组的指针,那么在析构函数中销毁它的正确方法是什么?
注意:我们的做法是在构造函数中将任何指针设置为 NULL。
I initialize it as a member variable.
int32_t *myArray_;
When I use it in a method, I would:
this->myArray = new int32_t[50];
To delete it in the method I would call delete on the array:
delete [] this->myArray;
What is the proper call in the destructor?
~MyDestructor(){
delete this->myArray_;
or delete [] this->myArray_;
}
关于向量指针我也有同样的问题:
I initialize it as a member variable.
std::vector<MyObject*> *myVector_;
When I use it in a method, I would:
this->myVector_ = new std::vector<MyObject*>();
//pushback some objects
To delete the vector in the method I would iterate the vector and delete its objects, then delete the vector;
for(std::vector<MyObject*>::iterator itr = this->myVector_->begin();
its != this->myVector->end(); ++ itr){
delete (*itr);
}
delete this->myVector_;
What would be the proper way to clean it up in the destructor?
would I just delete the vector?
delete this->myVector;
or do I need to iterate the entire vector again?
提前感谢您的任何建议。
【问题讨论】:
-
new[]-->delete[]和new-->delete. -
为什么会有
vector<>*?std::vector<>不会在堆栈上进行大量分配(在内部它从堆中分配对象),因此通常没有充分的理由动态分配std::vectors<>。 -
@Chad 使用向量指针是有正当理由的;一种情况是,如果 API 已经有工厂向您提供向量,但您有责任销毁它。
-
代码确实没有有一个“指向[n]
int32_t数组的指针”。它有一个指向int32_t的指针。 -
将内存管理强加给用户的 API 是邪恶的。
标签: c++ pointers memory-management