在模板化函数中使用unique_ptr ,vector 和int [](Work with unique_ptr, vector, and int[] in a Templatized Function)

假设我有3个变量:

vector<int> vec(3); int stat[3]; auto dyn = make_unique<int[]>(3);

如果我知道尺寸是3,我可以初始化其中的任何一个:

for(auto i = 0; i < 3; ++i) X[3] = i;

其中X是vec , stat或dyn 。 但我希望能够通过再次传入X来在模板中完成此操作。 我需要做的是:

包含的类型 容器大小

我可以通过以下功能获得该功能吗?

template <typename T> void init(T& X);

或者我无法从unique_ptr提取大小信息? 或者以通用的方式输入? (我已经在希望可以使用size的希望中标记了C ++ 17的这个问题。)

Say that I have 3 variables:

vector<int> vec(3); int stat[3]; auto dyn = make_unique<int[]>(3);

I can initialize any of these if I know the size is 3:

for(auto i = 0; i < 3; ++i) X[3] = i;

Where X is either, vec, stat, or dyn. But I'd like to be able to do this in a template just by passing in X again. What I'd need in order to do this is:

The contained type The container size

Can I get that in a function like:

template <typename T> void init(T& X);

Or am I unable to extract size information from the unique_ptr? Or type in a universal fashion? (I've marked this question C++17 in the hopes that size can be used.)

最满意答案

你不能从独特的指针获取大小。 当你使用auto dyn = make_unique<int[]>(3); 它被翻译成

make_unique<int[]>(new int[3]())

哪个是指针,我们丢失了大小信息。 对于唯一指针,所有的数组重载都会改变delete中的delete调用来delete[] 。 如果你想使用unique_ptr “数组”,那么你将需要通过大小。

You are not going to be able to get the size from the unique pointer. When you use auto dyn = make_unique<int[]>(3); it gets translated to

make_unique<int[]>(new int[3]())

Which is a pointer and we lose the size information. All the array overload does for unique pointer is change the delete call in the destruction to delete[]. If you want to use an unique_ptr "array" then you wil need to pass the size.

更多推荐