2

Is this safe?

std::unique_ptr<A> ptr(new A[100]);

When ptr goes out of scope and its destructor called, will it incorrectly delete the pointer, or delete[] it?

0

2 Answers 2

4

You have to correctly specify the type the unique_ptr will be holding for it to work correctly:

std::unique_ptr<A[]> ptr(new A[100]);

This will default to a deleter that uses delete[] instead of delete.

Sign up to request clarification or add additional context in comments.

Comments

2

If you correctly specify the pointed-to type as A[] it will correctly delete[] the pointer because there is a template specialization of unique_ptr for array types.

Note that you would not have had the opportunity to go wrong here if the type could be automatically inferred. That would require the expression that produces the pointer to be a function call (in the same vein as std::make_pair), like this:

auto ptr = make_unique(new A[100]);

This is a useful utility that's missing from C++11, but it has been added to C++14.

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.