【发布时间】:2022-08-04 00:22:15
【问题描述】:
我正在尝试将 list 的 shared_ptr\'s 转换为 int。当我尝试指向列表中的一个元素时,如果我有一个 shared_ptr 指向将指向该元素的对象,它会失败。
#include <iostream>
#include <list>
using namespace std;
class A
{
public:
A(){};
shared_ptr<int> p;
};
int main()
{
list<shared_ptr<int>> l;
l.push_back(make_shared<int>(1));
cout << \"counts to shared pointer: \" << l.back().use_count() << endl;
/* This works */
A a1;
a1.p = l.back();
cout << \"counts: \" << l.back().use_count() << endl;
/* This does not work */
shared_ptr<A> a2;
a2->p = l.back();
cout << \"counts: \" << l.back().use_count() << endl;
}
输出:
counts: 1
counts: 2
fish: Job 1, \'./l\' terminated by signal SIGSEGV (Address boundary error)
-
问问自己:对于
shared_ptr<A> a2;,A对象a2指向什么?
标签: c++ list shared-ptr