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?
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
: