![](/img/trans.png)
[英]Can I use a member variable of type ofstream initialized in the class constructor?
[英]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.