gpt4 book ai didi

c++ - 嵌套的 boost::shared_ptr use_count 不更新

转载 作者:行者123 更新时间:2023-11-30 02:41:53 26 4
gpt4 key购买 nike

我有一个嵌套的 boost::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;
}

output

use count before : 1

use count after: 1

use count before : 1

use count after: 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

查看 Live On Coliru


Brainwave 您是想将 storage_1 深度克隆到 storage_2 中吗?您似乎对您的外部 storage_2d_t 是也是共享指针这一事实感到困惑,因此您通过引用来引用相同的 vector 。

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++ - 嵌套的 boost::shared_ptr use_count 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com