问题
I am working against a blackbox framework (cdg), which fills an array of uint32_t with values.
The call looks like that:
std::size_t dataCount = 100;
uint32_t* data = new uint32_t[dataCount];
cdg.generate(data);
Unfortunately, the framework doesn't use templates, so I have to pass in a uint32_t*. To get rid of the raw pointer I want to "wrap" it into a std::unique_ptr<uint32_t>. Thus it is an array I think I have to use a
std::unique_ptr<uint32_t[]>. Is there a way to convert the raw pointer into a unique_ptr or should I do something like that:
const std::size_t dataCount = 100;
std::unique_ptr<uint32_t[]> data = std::make_unique<uint_32_t[]>(dataCount);
cdg.generate(data.get());
回答1:
Smart pointers are great and all, but perhaps consider using std::vector, since you note that it is an array.
You can get a pointer to the data as it were a C array (for your legacy interface) with data().
std::vector<uint32_t> nums(100); // creates a vector of size 100
uint32_t *ptr = nums.data();
cdg.generate(ptr); // passes uint32_t* as needed
If you need to ensure unique ownership, unique_ptr is the right choice. But it sounded like you really just wanted something that will clean up your array, but still gives a raw pointer for C methods.
来源:https://stackoverflow.com/questions/42271735/cast-raw-pointer-of-array-to-unique-ptr