Reputation: 463
As wiki shows, shared_ptr
can handle the heap space recycle problems.
So, I always use shared_ptr to create instance, is there any problems?
and I use it as this, i dont need to delete s
, right?
s = std::shared_ptr<S>(new S).get();
Upvotes: 1
Views: 2521
Reputation: 1420
You shouldn't always use shared_ptr
because there are more types of smart pointer than just shared_ptr
. The Standard Library also provides unique_ptr
for example. You must evaluate which better suits the task at hand.
Smart pointers in general are however the preferred way of safely handling dynamically allocated objects in modern C++. As a general rule of thumb, avoid the use of new
and delete
unless you encounter a problem that can't be solved without them.
As an aside, your example will not work as you expect.
auto s = std::shared_ptr(new S).get();
This will create a dangling pointer. The call to new
dynamically allocates an object of type S
. A pointer to it is given to the constructor for shared_ptr
which now manages the object lifetime. You then assign a copy of the raw pointer of S
to s
via get()
. At the end of the line the shared_ptr
destructor frees S
meaning that whatever s
points to is undefined.
The correct way to create a shared pointer would be:
auto s = std::make_shared<S>();
Upvotes: 3