Boost shared_ptr vector member access

时间:2015-08-07 12:18:56

标签: c++ algorithm boost

我对提升c ++库相当新,我有一个问题。

我的程序中有以下代码片段。

typedef std::vector<int> Indices;
typedef boost::shared_ptr<Indices> IndicesPtr;
...
IndicesPtr indices (new Indices);

将数据添加到索引后,我想使用operator []访问各个成员,我收到错误消息。

错误:错误:index [i]中的operator []不匹配。我不明白为什么会这样。使用boost :: shared_ptr&lt;&gt;时是否有特定的访问方式。

2 个答案:

答案 0 :(得分:3)

您不应在此使用shared_ptr,只使用vector,但如果您需要(例如进行培训),则可以使用

indices->operator[](index)

或取消引用shared_ptr

(*indices)[index]

就像原始指针一样。

答案 1 :(得分:2)

这种情况正在发生,因为boost :: shared_ptr没有operator [],std :: vector会。如果要访问向量&#39; s []运算符,则必须取消引用共享指针:

(*indices)[index]

如果你使用经典指针(*),你仍然会遇到类似的问题,但是在C ++中,指针[]将它视为一个数组(即使指针不是数组),在大多数情况下会导致分段错误(访问任何不同于0的单元时)