Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to check for nullptr when make_shared and make_unique is used?

If I am creating a pointer using make_shared or make_unique do I ever have to check whether it is nullptr or not, like:

std::unique_ptr<class> p = std::make_unique<class>();
if (p == nullptr)
{
    ....
    ....
}

If you’re really running out of memory, std::make_unique will through an expection. So you will never get a null pointer from std::make_unique. Is this correct ?

So there's no need to check for nullptr when you do make_shared and make_unique?

like image 740
jack sparow Avatar asked Jul 18 '19 08:07

jack sparow


People also ask

What is the purpose of a null shared_ptr?

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. But we might utilize a non-empty shared_ptr 's deleter to execute arbitrary cleanup code on block exit.

Can a nullptr be interpreted as a handle to any type?

The following code example shows that nullptr is interpreted as a handle to any type or a native pointer to any type. In case of function overloading with handles to different types, an ambiguity error will be generated. The nullptr would have to be explicitly cast to a type.

How to create a shared_ptr that is empty but still pointing?

With aliasing constructor, we can create a shared_ptr that points to an object but shares the ownership of a completely unrelated object. Here is an example of how we create a shared_ptr that is empty but still pointing to an object: int x = 100; //'px' holds &x, but is empty.

Where can the nullptr keyword be used?

The following code example demonstrates that the nullptr keyword can be used wherever a handle, native pointer, or function argument can be used. And the example demonstrates that the nullptr keyword can be used to check a reference before it is used.


1 Answers

From cppreference on std::make_unique (similar for std::make_shared):

Exceptions

May throw std::bad_alloc or any exception thrown by the constructor of T. If an exception is thrown, this function has no effect.

"This function has no effect" specifically means that it doesn't return anything because the exception handling mechanism kicks in. So yes, your assumption is right. Error handling in std::make_unique is done by exceptions, and the return value is never nullptr.

like image 132
lubgr Avatar answered Nov 15 '22 13:11

lubgr