【问题标题】:Understanding vector<shared_ptr<T> >, shared_ptr<vector<T> >, or vector<T>了解 vector<shared_ptr<T> >、shared_ptr<vector<T> > 或 vector<T>
【发布时间】:2013-06-07 15:07:26
【问题描述】:

Node是我们解析图时用来存储Node的数据结构。

这里是示例代码:

struct NodeA {
    vector<string> vecStrs; // the size of the vecStrs keeps increasing!
};
struct NodeB {
    vector<boost::shared_ptr<string> > vecShpStrs;
};

struct NodeC {
    boost::shared_ptr<vector<string> > shpVecStrs;
};

int main()
{
    NodeA nodeA;
    nodeA.vecStrs.push_back("stringA");    // input
    cout << "Output from NodeA: " << nodeA.vecStrs.front() << endl; // output

    NodeB nodeB;
    nodeB.vecShpStrs.push_back(boost::make_shared<string>("stringB"));
    cout << "Output from NodeB: " << *(nodeB.vecShpStrs.front()) << endl;

    NodeC nodeC;
    nodeC.shpVecStrs.reset(new vector<string>());
    nodeC.shpVecStrs->push_back("stringC");
    cout << "Output from NodeC: " << nodeC.shpVecStrs->front() << endl;
}

请验证我的理解是否正确

问题 1.1> 每当复制 NodeB 的实例时,存储在向量中的元素集合也会被复制。由于每个元素都是一个 shared_ptr,因此复制操作比 NodeA 更便宜。

问题 1.2> 每当复制 NodeC 的实例时,唯一复制的元素是 shared_ptr,而底层向量不会被复制,而是在所有引用的 shared_ptr 之间共享。

问题2> 应该使用NodeC的工具来使副本成本最低。如果是这样的话(我怀疑),为什么我大部分时间看到的是 NodeB 而不是 NodeC 的使用?

谢谢

【问题讨论】:

    标签: c++ boost stl


    【解决方案1】:

    1.1) 正确

    1.2) 正确

    2.0) 因为 boost::shared_ptr 的主要用途不是提供廉价副本,而是管理生命周期。否则,原始指针也足够了。向量通常被定义为成员对象,并随其父对象自动销毁,其中位于向量中的对象被插入、移除和移动。

    【讨论】:

      【解决方案2】:

      问题2> 应该使用NodeC的工具来制作副本 最便宜的。如果是这样(我怀疑),为什么我看到 大部分时间是 NodeB 而不是 NodeC?

      正如 enigma 所说,使用 NodeC 进行复制是错误的,因为您没有复制向量,只是共享它(复制智能指针)。例如:

      NodeC nodeC;
      nodeC.shpVecStrs.reset(new vector<string>());
      nodeC.shpVecStrs->push_back("stringC");
      assert(nodeC.shpVecStrs->size() == 1);
      
      NodeC nodeC2 = nodeC;
      nodeC2.shpVecStrs->push_back("other string");
      assert(nodeC2.shpVecStrs->size() == 2);
      assert(nodeC.shpVecStrs->size() == 2); // they are the same pointer.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-20
        • 2018-02-02
        • 2017-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-06
        • 1970-01-01
        相关资源
        最近更新 更多