我需要删除一个向量吗?

Nap*_*don 1 c++

我将vector定义为Grid类的私有变量.Class Points只有两个实例变量,它们都是整数,但只有当我从文件中读取它时,才会知道点的数量,所以我想我必须用new动态创建Points,这意味着我必须在以后销毁它们.我是否正确地初始化了构造函数?当为Grid编写析构函数时,我需要为这样的向量编写析构函数:~vecotr()或删除或使用迭代器?

class Grid{
public:
  // initialize vector with 3 points with val 0.
  Grid(vector<Points> v) : vector<Points>(3, 0) {};  // is this right


// first option
  ~Grid() {
    ~vector<Points>();  // not sure how to destroy vector<Points>;
  }

// second option
  ~Grid() {
     delete v_points;
  }

// third option
  ~Grid() {
     for (vector<Points>::iterator it = v_points.begin(), 
          vector<Points>::iterator it_end = v_points.end(); it != it_end; it++)
  }

private:
  vector<Points> v_points;
};
Run Code Online (Sandbox Code Playgroud)

我应该使用哪个选项并正确初始化构造函数?

Any*_*orn 9

如果没有分配对象new,则不需要显式销毁它.成员对象将按其声明的相反顺序自动销毁.在你的情况下,甚至不需要创建析构函数,因为自动化就足够了.

如果由于某种原因您确实使用new分配了成员对象,则还必须创建自定义复制构造和赋值运算符,否则会遇到跨多个实例共享同一成员对象的麻烦.