嵌套提升::shared_ptr use_count未更新
nested boost::shared_ptr use_count not updating
我有一个嵌套的提升::shared_ptr,当被分配到另一个并超出范围时,它偶尔会被破坏。我发现除非我将指针复制到临时,否则use_count不会更新。该代码是不言自明的。在第一个 for 循环中,use_count不会更新,而在另一个循环中更新。
#include <vector>
#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
typedef int T;
typedef std::vector<T> content_1d_t;
typedef boost::shared_ptr<content_1d_t> storage_1d_t;
typedef std::vector<storage_1d_t> content_2d_t;
typedef boost::shared_ptr<content_2d_t> storage_2d_t;
int dim1 = 10;
int dim2 = 1;
content_2d_t* content_1 = new content_2d_t();
content_1->reserve(dim2);
storage_2d_t storage_1(content_1);
for (int i = 0; i < dim2; ++i)
{
storage_1->push_back(storage_1d_t(new content_1d_t(dim1)));
}
//content_2d_t* content_2 = new content_2d_t(dim2);
storage_2d_t storage_2 = storage_1;
for (int i = 0; i < dim2; ++i)
{
cout<< "use count before : "<< storage_1->operator[](i).use_count()<<endl;
storage_2->operator[](i) = storage_1->operator[](i);
cout<< "use count after: "<< storage_1->operator[](i).use_count()<<endl;
}
for (int i = 0; i < dim2; ++i)
{
cout<< "use count before : "<< storage_1->operator[](i).use_count()<<endl;
storage_1d_t ref = storage_1->operator[](i);
storage_2->operator[](i) = ref;
cout<< "use count after: "<< storage_1->operator[](i).use_count()<<endl;
}
/* code */
return 0;
}
输出
使用前计数 : 1
使用后计数:1
使用前计数 : 1
使用后计数:2
由于您显然storage_2d_t storage_2 = storage_1;
,因此将元素直接分配回自身不应增加使用计数。
我第二个循环,你打印使用计数期间你持有临时副本(ref
(。明确地说,您可以看到确实 - 正如预期的那样 - "之后"计数实际上并不高:
for (int i = 0; i < dim2; ++i) {
cout << "use count before : " << (*storage_1)[i].use_count() << endl;
{
storage_1d_t ref = (*storage_1)[i];
(*storage_2)[i] = ref;
cout << "use count during: " << (*storage_1)[i].use_count() << endl;
}
cout << "use count after: " << (*storage_1)[i].use_count() << endl;
}
现在打印
use count before : 1
use count during: 2
use count after: 1
在科里鲁现场观看
脑电波 你的意思是将storage_1
深度克隆到storage_2
吗?看来您对以下事实感到困惑:您的外部storage_2d_t也是一个共享指针,因此您通过引用引用相同的向量。
storage_2d_t storage_2 = boost::make_shared<content_2d_t>(*storage_1);
// or
storage_2d_t storage_2 = boost::make_shared<content_2d_t>(storage_1->begin(), storage_1->end());
相关文章:
- 从C++本机插件更新Vector3数组
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- cmake更新缓存的变量
- 更新到莫哈韦后出现cmath错误
- OpenMP:并行更新数组总是需要减少数组吗
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 指针没有更新它在void函数内部指向的值
- 如何在c++中获取要更新的值
- 已修改的LinkedList未在文本文件本身中更新
- Qt:当QListView获得新条目时,如何更新QStringList
- 更新的矢量元素不打印
- DrawIndexedInstanced 具有不同的 Index Count per Instance (Directx
- 如何使用按钮更新GTK3图像以使用C++从相机捕获图片
- 如何在ECS框架中更新组件数据和通知系统
- 从VS 2015更新3更新到VS2015更新3 d后浮点计算行为不同的原因
- 如果我想在没有更新编译器的情况下使用新功能,该怎么办?
- 如何在 C++11 中查找和更新向量中的一个嵌套结构
- (SFML)按下键时,播放器构造函数未使用正确的动画进行更新
- 在 emscripten 网页汇编正在运行期间更新进度条?
- 在运行时使用范围更新结果