Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 When clearing shared_ptr, should I use reset or set to nullptr?

I have a question about C++11 best practices. When clearing a shared_ptr, should I use the reset() function with no parameter, or should I set the shared_ptr to nullptr? For example:

std::shared_ptr<std::string> foo(new std::string("foo")); foo.reset(); foo = nullptr; 

Is there any real difference, or are there advantages/disadvantages to either approach?

like image 944
user1930581 Avatar asked Apr 22 '13 16:04

user1930581


People also ask

What is the best way to delete an object managed by shared_ptr?

If shared_ptr::unique returns true, then calling shared_ptr::reset will delete the managed object.

Can shared_ptr be Nullptr?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .

What happens when you reset a shared pointer?

std::shared_ptr<T>::reset. Replaces the managed object with an object pointed to by ptr . Optional deleter d can be supplied, which is later used to destroy the new object when no shared_ptr objects own it. By default, delete expression is used as deleter.

Should I use shared_ptr or Unique_ptr?

Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.


1 Answers

Is there any real difference, or are there advantages/disadvantages to either approach?

The two alternatives are absolutely equivalent, in the sense that the second form (foo = nullptr) is defined in terms of the first one. Per Paragraph 20.7.1.2.3/8-10 of the C++11 Standard:

 unique_ptr& operator=(nullptr_t) noexcept; 

8 Effects: reset().

9 Postcondition: get() == nullptr

10 Returns: *this.

Therefore, just choose the one which makes its intent clearest for you. Personally, I prefer:

foo = nullptr; 

Because it makes it more evident that we want the pointer to be null. As a general advice, however, try to minimize the situations where you need to explicitly reset a smart pointer.


Besides, rather than using new:

std::shared_ptr<std::string> foo(new std::string("foo")); 

Consider using std::make_shared() when possible:

auto foo = std::make_shared<std::string>("foo"); 
like image 67
Andy Prowl Avatar answered Sep 19 '22 00:09

Andy Prowl