I have an array of (for example) uint8_t
s.
Is std::unique_ptr
the wrong tool to use to manage this object in memory?
For example,
std::unique_ptr<uint8_t> data(new uint8_t[100]);
Will this produce undefined behaviour?
I want a smart-pointer object to manage some allocated memory for me. std::vector
isn't ideal, because it is a dynamic object. std::array
is no good either, because the size of allocation is not known at compile time. I cannot use the [currently, 2016-03-06] experimental std::dynarray
, as this is not yet available on Visual Studio 2013.
Unfortunately I have to conform to VS2013, because, rules.
The way you're using the unique_ptr
will indeed result in undefined behavior because it'll delete
the managed pointer, but you want it to be delete[]
d instead. unique_ptr
has a partial specialization for array types to handle such situations. What you need is
std::unique_ptr<uint8_t[]> data(new uint8_t[100]);
You can also use make_unique
for this
auto data = std::make_unique<uint8_t[]>(100);
There is a subtle difference between the two, however. Using make_unique
will zero initialize the array, while the first method won't.
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