Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 理解向量<;共享\u ptr<;T>>;,共享\u ptr<;向量<;T>>;,或向量<;T>;_C++_Boost_Stl - Fatal编程技术网

C++ 理解向量<;共享\u ptr<;T>>;,共享\u ptr<;向量<;T>>;,或向量<;T>;

C++ 理解向量<;共享\u ptr<;T>>;,共享\u ptr<;向量<;T>>;,或向量<;T>;,c++,boost,stl,C++,Boost,Stl,节点是在解析图时用于存储节点的数据结构 以下是示例代码: 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<ve

节点是在解析图时用于存储节点的数据结构

以下是示例代码:

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;
}
结构节点a{ vector vecStrs;//vecStrs的大小不断增加! }; 结构节点B{ 向量向量strs; }; 结构节点{ boost::共享_ptr shpVecStrs; }; int main() { NodeA NodeA; nodeA.vecStrs.push_back(“stringA”);//输入 cout1.1)正确

1.2)正确

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

问题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.
NodeC-NodeC;
重置(新向量());
nodeC.shpVecStrs->push_back(“stringC”);
断言(nodeC.shpVecStrs->size()=1);
NodeC nodeC2=NodeC;
nodeC2.shpVecStrs->push_back(“其他字符串”);
断言(nodeC2.shpVecStrs->size()=2);
assert(nodeC.shpVecStrs->size()==2);//它们是相同的指针。