Proper way to create unique_ptr that holds an allocated array
Using the T[]
specialisation:
std::unique_ptr<unsigned char[]> testData(new unsigned char[16000]());
Note that, in an ideal world, you would not have to explicitly use new
to instantiate a unique_ptr
, avoiding a potential exception safety pitfall. To this end, C++14 provides you with the std::make_unique
function template. See this excellent GOTW for more details. The syntax is:
auto testData = std::make_unique<unsigned char[]>(16000);
Use the array version :
auto testData = std::unique_ptr<unsigned char[]>{ new unsigned char[16000] };
Or with c++14, a better form ( VS2013 already has it ):
auto testData = std::make_unique<unsigned char[]>( 16000 );
A most likely better way would be to use std::vector<unsigned char>
instead
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<unsigned char> testData(0x12, 0); // replaces your memset
// bla
}
The advantage is that this is much less error-prone and gives you access to all kinds of features such as easy iteration, insertion, automatic reallocation when capacity has been reached.
There is one caveat: if you are moving your data around a lot, a std::vector
costs a little more because it keeps track of the size and capacity as well, rather than only the beginning of the data.
Note: your memset
doesn't do anything because you call it with a zero count argument.