【问题标题】:Pointing from a shared_ptr to a list yields memory error从 shared_ptr 指向列表会产生内存错误
【发布时间】:2022-08-04 00:22:15
【问题描述】:

我正在尝试将 listshared_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&lt;A&gt; a2;A 对象a2 指向什么?

标签: c++ list shared-ptr


【解决方案1】:
/* This does not work */
shared_ptr<A> a2;
a2->p = l.back();

它不应该工作。 a2 是一个不拥有任何东西的共享指针。然而,你-&gt;-derefence 它。你认为a2 拥有的A 不存在!您需要制作一个,例如,就像您对 int 使用 make_shared 所做的那样。

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2020-03-18
    • 2020-01-09
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多