了解矢量<shared_ptr<T>>、shared_ptr<矢量<T>>或矢量<T>
Understanding vector<shared_ptr<T> >, shared_ptr<vector<T> >, or vector<T>
节点是我们解析图时用来存储节点的数据结构。
下面是示例代码: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;
}
请验证我的理解是否正确
Question 1.1>每当复制NodeB的实例时,存储在vector中的元素集合也被复制。由于每个元素都是shared_ptr,因此与NodeA相比,复制操作的成本更低。
>每当复制NodeC的实例时,唯一复制的元素是shared_ptr,而底层向量不被复制,而是在所有引用的shared_ptr中共享。
问题2> NodeC的实现应该用来使拷贝成本最低。如果是这样的话(我怀疑),为什么我看到大多数时候使用NodeB而不是NodeC?
谢谢
1.1)正确
1.2)正确
2.0)因为boost::shared_ptr的主要用途不是提供廉价的副本,而是管理生命周期。否则,原始指针也足够了。vector通常被定义为成员对象,并与其父对象一起自动销毁,其中位于vector中的对象将被插入、删除和移动。
Question 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.
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中