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?
CodePudding user response:
std::shared_ptr
can't be copy-initialized from raw pointer, the conversion constructor is marked as explicit
.
You can use direct-initialization:
class Foo {
public:
std::shared_ptr<int> intSharedPtr {new int};
Foo() {}
};
Or initialize from an std::shared_ptr
:
class Foo {
public:
std::shared_ptr<int> intSharedPtr = std::shared_ptr<int>(new int);
Foo() {}
};
And better to use std::make_shared
:
class Foo {
public:
std::shared_ptr<int> intSharedPtr = std::make_shared<int>();
Foo() {}
};