用的unique_ptr&LT工作; INT []>中矢量< INT>和INT []在模板化功能 [英] Work with unique_ptr<int[]>, vector<int>, and int[] in a Templatized Function

查看:98
本文介绍了用的unique_ptr&LT工作; INT []>中矢量< INT>和INT []在模板化功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有3个变量:

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

我可以初始化任何这些,如果我知道的大小是3:

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

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

其中, X VEC 与stat DYN 。不过,我想能够做到这一点的模板只需在通过X 一次。什么我需要在为了做到这一点是:

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:


  1. 被包容的类型

  2. 容器大小<​​/ li>
  1. The contained type
  2. The container size

我可以在一个功能,如:

Can I get that in a function like:

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

还是我无法提取从尺寸信息的unique_ptr ?或者在通用时尚型? (我在的希望打上这个问题,C ++ 17的 尺寸 < /一>可以被使用。)

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.)

推荐答案

您不会能够从独特的指针获得的大小。当您使用自动DYN = make_unique&LT; INT []&GT;(3); 它被翻译成

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]())

这是一个指针,我们失去了大小信息。所有阵列超载确实为唯一指针更改破坏删除调用删除[] 。如果你想使用的unique_ptr 阵列,那么你西港岛线需要传递的大小。

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.

这篇关于用的unique_ptr&LT工作; INT []&gt;中矢量&lt; INT&gt;和INT []在模板化功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆