Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::unique_ptr the wrong tool to allocate memory for an array?

I have an array of (for example) uint8_ts.

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.

like image 584
FreelanceConsultant Avatar asked Dec 02 '22 15:12

FreelanceConsultant


1 Answers

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.

like image 148
Praetorian Avatar answered May 20 '23 10:05

Praetorian