Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong to reset std::unique_ptr to pointer to array?

I see some code snippet like below:

std::unique_ptr<uint8_t> mCache;
mCache.reset(new uint8_t[size]);

Someone told me there are some problems with this code. Can anyone give me some details?

like image 845
jiych.guru Avatar asked Aug 15 '18 08:08

jiych.guru


People also ask

What does unique_ptr Reset do?

std::unique_ptr::reset Destroys the object currently managed by the unique_ptr (if any) and takes ownership of p. If p is a null pointer (such as a default-initialized pointer), the unique_ptr becomes empty, managing no object after the call.

Do I need to delete unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.

What happens when you move a unique_ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it.

What happens when unique_ptr goes out of scope?

unique_ptr. An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope.


1 Answers

Given std::unique_ptr<uint8_t> mCache;, when mCache is destroyed its deleter will use delete to destroy the pointer being managed (if any), i.e. to deallocate memory for a single object. But after mCache.reset(new uint8_t[size]); what mCache manages is a pointer to array, that means it should use delete[] instead; using delete to deallocate memory for an array leads to UB.

The code could be changed to

std::unique_ptr<uint8_t[]> mCache; // mCache is supposed to manage pointer to array
mCache.reset(new uint8_t[size]);   // safe now
like image 169
songyuanyao Avatar answered Oct 18 '22 12:10

songyuanyao