簡體   English   中英

如何將其切換為unique_ptr?

[英]How do I switch this to unique_ptr?

我如何做到這一點,所以我不必手動刪除指針?

vector<>unique_ptr嗎?

這是我的代碼:

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

簡單:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM