9

我想问几个关于正确销毁 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?

提前感谢您的任何建议。

4

1 回答 1

15

任何分配的东西new都应该用 释放delete

int* p = new int;
delete p;

任何分配的东西new []都应该用 释放delete []

int* p = new int[10];
delete [] p;

任何动态分配和存储在 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);

如果出于某种奇怪的原因,您认为动态分配 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;

但是,我建议动态分配 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!

如果您有一个类的成员变量,则适用相同的规则:

class Foo
{
   Foo()
      : bar_(new int)
      , bar2_(new int[20])
   {
   }

   ~Foo()
   {
      delete [] bar2_;
      delete bar_;
   }

   int* bar_;
   int* bar2_;
};

但即便如此,将它们设置为 更有意义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_;
};
于 2012-12-12T17:15:52.827 回答