为什么智能指针类型的成员变量不能在类的声明处初始化?
当我想向类中添加一个智能指针类型的成员变量时,我发现它无法在声明处初始化:
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);
}
};
看来智能指针与普通指针有很大不同,为什么会发生这种情况吗?
When I want to add a member variable with smart pointer type to a class, I found that it can't be initialized at the declaring place:
class Foo {
public:
std::shared_ptr<int> intSharedPtr = new int; // not ok
Foo() {}
};
But I can do this:
class Foo {
public:
std::shared_ptr<int> intSharedPtr; // ok
int* intPtr = new int; // ok
Foo() {
intSharedPtr.reset(new int);
}
};
It seems that smart pointer is quite different form the normal pointer, Why this happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std :: shared_ptr
不能 copy-initialized 来自RAW指针,转换构造函数被标记为explicit
。您可以使用 direct-initialization :
或从
std :::::::::: sharon_ptr
:最好使用
std :: make_shared
:
std::shared_ptr
can't be copy-initialized from raw pointer, the conversion constructor is marked asexplicit
.You can use direct-initialization:
Or initialize from an
std::shared_ptr
:And better to use
std::make_shared
: