3

I have not been able to find any documentation about what happens if I pass a null pointer to std::make_unique.

Is an exception thrown?

3
  • 2
    What is the underlying reason for the question? Why do you think that there's something unusual or extraordinary in passing null pointer to make_unique? How is passing null pointer different from passing, say. 42 or "Hello World"? Commented Jul 11, 2019 at 16:38
  • 1
    make_unique does not take a pointer and "make it unique", it creates ("makes") an object that has unique and transferrable ownership. std::make_unique<int*>(nullptr) creates a null int* with those properties. Commented Jul 11, 2019 at 16:42
  • 1
    Show the code demonstrating what you're really asking about, because frankly the question as/is doesn't make sense. std::make_unqiue<Type> creates a dynamic Type instance and assigns ownership to the then-returned std::unique_ptr<Type> object. This sounds like you think std::make_unique does something else, or your confusing std::make_unique with the constructor for std::unique_ptr; they're different beasts. Commented Jul 11, 2019 at 16:46

2 Answers 2

9

std::make_unique forwards all the arguments passed to a matching target constructor. Therefore, if you pass nullptr, it will search for a constructor that accepts nullptr_t (or any matching constructor). If it is not there, it will fail to compile.

class A
{
public:
   A(void*) { ... } // could also be A(int*) or template <typename T> A(T*)
};

...
std::make_unique<A>(nullptr); // constructs an A by calling A(void*), passing nullptr.
Sign up to request clarification or add additional context in comments.

1 Comment

It is not necessary that the constructor had the declaration A( void * ). It can be for example A( int * ); or A( T *ptr, Args ...args );
5

std::make_unique is meant to construct an object wrapped by forwarding the arguments to the constructor of the wrapped object.

Passing nullptr to it doesn't make any sense in the way you mean. If you need to clear the content of a std::unique_ptr just call reset().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.