如何将其切换为unique_ptr?

时间:2018-08-25 07:09:47

标签: c++ c++11 unique-ptr

我如何做到这一点,所以不必手动删除指针?

unique_ptr中有vector<>吗?

这是我的代码:

class vec2 {
 public:
  double x;
  double y;

  vec2() {
    x = 0.0;
    y = 0.0;
  }

  vec2(double xx, double yy) {
    x = xx;
    y = yy;
    cout << "constructor called" << endl;
  }

  ~vec2() {
    static int count = 0;
    cout << "destructor " << count << endl;
    count++;
  }

  virtual double Length() { return sqrt(x * x + y * y); }

  bool operator==(vec2& v) { return x == v.x && y == v.y; }

  virtual string toString() {
    stringstream s("");
    s << "[" << x << " " << y << "]";
    return s.str();
  }
};

int main() {
  vector<vec2*> vecs;
  vecs.push_back(new vec2(1.8, 1.7));
  vecs.push_back(new vec2(1.99, 1.7));
  for (vec2* v : vecs) {
    cout << v->toString() << endl;
    delete v;
  }
}

http://www.xgdev.com/notepad/textfiles/37631a.txt

1 个答案:

答案 0 :(得分:2)

简单:

std::vector<std::unique_ptr<vec2>> vecs;
vecs.reserve(2);   // Optional
vecs.push_back(std::make_unique<vec2>(1.8 ,1.7));
vecs.push_back(std::make_unique<vec2>(1.99, 1.7));
for (auto& v : vecs) {
    cout << v->toString() << endl;
}

如果您有virtual个成员函数,则最有可能的是,析构函数也应该是virtual