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?
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.
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.
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.
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.
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
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