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
?
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.
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.
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.
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.
From cppreference on std::make_unique
(similar for std::make_shared
):
Exceptions
May throw
std::bad_alloc
or any exception thrown by the constructor ofT
. 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With