Mie*_*iek 9 c++ pointers memory-management
我想问一些关于正确销毁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_;
}
Run Code Online (Sandbox Code Playgroud)
我对矢量指针有同样的问题:
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?
Run Code Online (Sandbox Code Playgroud)
提前感谢任何建议.
Cha*_*had 14
分配的任何内容new
都应该被取消分配delete
.
int* p = new int;
delete p;
Run Code Online (Sandbox Code Playgroud)
分配的任何内容new []
都应该被取消分配delete []
.
int* p = new int[10];
delete [] p;
Run Code Online (Sandbox Code Playgroud)
动态分配和存储在a中的任何内容都vector
需要手动解除分配:
std::vector<int*> v;
v.push_back(new int(1));
v.push_back(new int(2));
for(std::vector<int*>::iterator i = v.begin(), e = v.end(); i != e; ++i)
delete (*i);
Run Code Online (Sandbox Code Playgroud)
如果由于某种奇怪的原因,您认为动态分配a是合适的vector
,则适用相同的规则.
std::vector<int*>* v = new std::vector<int*>;
v->push_back(new int(1));
v->push_back(new int(2));
for(std::vector<int*>::iterator i = v->begin(), e = v->end(); i != v; ++i)
delete (*i);
delete v;
Run Code Online (Sandbox Code Playgroud)
但是,我建议动态分配a的原因std::vector
很少.
在C++ 11中,最好的方法是std::unique_ptr
:
std::unique_ptr<int> p(new int);
// std::unique_ptr handles clean up for you
std::unique_ptr<int[]> p(new int[10]);
// std::unique_ptr handles clean up for you for arrays too!
Run Code Online (Sandbox Code Playgroud)
如果您有一个类的成员变量,则适用相同的规则:
class Foo
{
Foo()
: bar_(new int)
, bar2_(new int[20])
{
}
~Foo()
{
delete [] bar2_;
delete bar_;
}
int* bar_;
int* bar2_;
};
Run Code Online (Sandbox Code Playgroud)
但即便如此,将它们作为更有意义的是std::unique_ptr
,您甚至可以在需要时将它们视为接口中的原始指针:
class Foo
{
Foo()
: bar_(new int)
, bar2_(new int[20])
{
}
int* get_bar()
{
return bar_.get();
}
int* get_bar2()
{
return bar2_.get();
}
std::unique_ptr<int> bar_;
std::unique_ptr<int[]> bar2_;
};
Run Code Online (Sandbox Code Playgroud)