我想问几个关于正确销毁 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?
提前感谢您的任何建议。