共享指针 [] 运算符和 ++ 运算符

Shared pointer [] operator and ++ operator

我们可以使用 [] 运算符或带有唯一指针的 ++ 或 shared_pointer 吗?当我们将它用于原始指针时

int * a = new int[10];
a[0] = 2; // We can use [] operator;

两者 std::unique_ptr and std::shared_ptr 都提供 operator[] 用于对存储数组进行索引访问。如果他们管理的是数组,则可以使用它们。

operator[] provides access to elements of an array managed by a unique_ptr.

例如

std::unique_ptr<int[]> a(new int[10]);
a[0] = 2; // We can use [] operator;

注意下标要小于数组中的元素个数;否则,行为未定义。

很遗憾,我们不能直接对它们使用 operator++;这不是 smart pointers 应该做的,它们通常用于管理指针。

如果您只想要一个数组,我建议您使用 std::vectorstd::array

是的。

这是一个例子 http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_at

 std::unique_ptr<int[]> fact(new int[size]);