簡體   English   中英

為什么在class的聲明處不能初始化智能指針類型的成員變量?

[英]Why smart pointer type member variable can't be initialized at the declaring place in a class?

當我想給一個class添加一個智能指針類型的成員變量時,發現在聲明的地方無法初始化:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr = new int;  // not ok
  Foo() {}
};

但我可以這樣做:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr;  // ok
  int* intPtr = new int; // ok
  Foo() {
    intSharedPtr.reset(new int);
  }
};

看起來智能指針與普通指針有很大不同,為什么會這樣?

std::shared_ptr不能從原始指針 復制初始化轉換構造函數被標記為explicit

您可以使用直接初始化

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr {new int};
  Foo() {}
};

或者從std::shared_ptr初始化:

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr = std::shared_ptr<int>(new int);
  Foo() {}
};

最好使用std::make_shared

class Foo {
 public:
  std::shared_ptr<int> intSharedPtr = std::make_shared<int>();
  Foo() {}
};

暫無
暫無

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

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