【问题标题】:Shared pointer [] operator and ++ operator共享指针 [] 运算符和 ++ 运算符
【发布时间】:2016-10-21 06:44:32
【问题描述】:

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

int * a = new int[10];
a[0] = 2; // We can use [] operator;
  • 智能指针有类似的方法吗?

  • 如果有的话应该什么时候用这个?

  • 如果不存在那为什么?
  • 多维数组也可以吗?

【问题讨论】:

标签: c++ arrays pointers smart-pointers


【解决方案1】:

std::unique_ptrstd::shared_ptr 都提供 operator[] 用于对存储数组的索引访问。如果他们管理的是数组,您可以使用它们。

operator[] 提供对由unique_ptr 管理的数组元素的访问。

例如

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

注意索引必须小于数组中的元素个数;否则,行为未定义。

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

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

【讨论】:

  • 它是指向 int[] 的指针,而不是在原始指针的情况下指向 int 的指针。我们也可以使用 ++ 运算符吗?
  • @Anshuman 你指的是什么指针?它们提供与原始指针相同的行为。是的,我们不能直接在他们身上使用operator++;这不是智能指针应该做的。
  • 谢谢,多维数组呢
  • @Anshuman 基本上它们是相同的,二维数组仍然可以被视为某物的一维数组(即数组)。但是将它与智能指针一起使用似乎令人困惑,您可以使用std::vectorstd::array,如std::vector&lt;std::vector&lt;T&gt;&gt;
【解决方案2】:

是的。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 2013-05-26
    • 2017-06-20
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 2021-07-02
    • 2013-07-22
    相关资源
    最近更新 更多