Ans*_*man 2 c++ arrays pointers smart-pointers
我们可以将 [] 运算符或 ++ 与唯一指针或 shared_pointer 一起使用吗?当我们将它用于原始指针时
int * a = new int[10];
a[0] = 2; // We can use [] operator;
Run Code Online (Sandbox Code Playgroud)
智能指针有类似的方法吗?
如果有,我应该什么时候使用它?
两者的std ::的unique_ptr和性病:: shared_ptr的提供operator[]对索引的访问所存储的数组中。如果他们管理的是数组,您可以使用它们。
operator[]提供对由 a 管理的数组元素的访问unique_ptr。
例如
std::unique_ptr<int[]> a(new int[10]);
a[0] = 2; // We can use [] operator;
Run Code Online (Sandbox Code Playgroud)
请注意,索引应小于数组中的元素数;否则,行为未定义。
不幸的是,我们不能operator++直接使用它们;这不是智能指针应该做的,它们通常用于管理指针。
我建议你使用std::vector或者std::array如果你只想要一个数组。
| 归档时间: |
|
| 查看次数: |
645 次 |
| 最近记录: |