Cast raw pointer of array to unique_ptr

走远了吗. 提交于 2019-12-10 11:26:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!