Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use make_unique or reset() for already defined smart pointers?

Tags:

c++

c++11

Suppose I have a function that optionally allocates an object and returns it:

// Class member
std::deque<Packet> m_receiveQueue;

// Function in class that operates on the queue
template<typename T>
std::unique_ptr<T> Get()
{
  std::unique_ptr<T> response;

  if (!m_receiveQueue.empty())
  {
     response = std::make_unique<T>(m_receiveQueue.front());
     m_receiveQueue.pop();
  }

  return response;
}

Should I instead do:

response.reset(new T{m_receiveQueue.front()});

Why or why not? Also does the same advice apply to other smart pointers, such as shared_ptr? Just looking for a best practice.

like image 900
void.pointer Avatar asked Dec 20 '16 17:12

void.pointer


People also ask

What is the difference between the two smart pointers shared_ptr and unique_ptr?

In short: 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.

What does unique_ptr Reset do?

unique_ptr::resetReplaces the managed object. 1) Given current_ptr , the pointer that was managed by *this, performs the following actions, in this order: Saves a copy of the current pointer old_ptr = current_ptr. Overwrites the current pointer with the argument current_ptr = ptr.

Do smart pointers automatically delete?

Smart pointers perform automatic memory management by tracking references to the underlying object and then automatically deleting that object when the last smart pointer that refers to that object goes away. Here is an example to demonstrate how this works.

Do you need to delete smart pointers?

So, we don't need to delete it as Smart Pointer does will handle it. A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.


1 Answers

Don't do it, use the std::make_unique one.

If I were to look at your code, and see a call to reset, I might wonder what pointer the smart pointer was referring to before, and try to find the code where you change ownership of that pointer. But the smart pointer is empty in your case!

That's weird, why would you call reset on a empty pointer, it is already empty/"reset". Try to code so that your intent is better and clear, in this case, even though both are technically equivalent in your case, use std::make_unique. It better describes what you are trying to do (initializing a new smart pointer, not changing the ownership of it).

like image 71
Rakete1111 Avatar answered Sep 20 '22 16:09

Rakete1111