将数组的原始指针转换为unique_ptr [英] Cast raw pointer of array to unique_ptr
问题描述
我正在使用黑盒框架(cdg),该框架用值填充uint32_t
的数组.
呼叫看起来像这样:
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);
不幸的是,该框架未使用模板,因此我必须传递uint32_t*
.为了摆脱原始指针,我想将其包装"到std::unique_ptr<uint32_t>
中.因此,这是一个数组,我想我必须使用
std::unique_ptr<uint32_t[]>
.有没有一种方法可以将原始指针转换为unique_ptr
,或者我应该做类似的事情:
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());
推荐答案
智能指针非常有用,但最好考虑使用std::vector
,因为您注意到它是一个数组.
Smart pointers are great and all, but perhaps consider using std::vector
, since you note that it is an array.
您可以使用获取指向数据的指针,因为它是C数组(对于您的旧版接口). data()
.
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
如果您需要确保唯一的所有权,那么unique_ptr
是正确的选择.但这听起来像是您确实只想要一些可以清理数组的东西,但仍然提供了C方法的原始指针.
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.
这篇关于将数组的原始指针转换为unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!