小编sch*_*lig的帖子

稍后设置std :: shared_ptr源

我刚刚开始使用C++并试图了解智能指针.显然,下面的代码会崩溃(我想这是因为赋值创建了shared_ptr的副本?).有没有办法foo.Other通过调用某种set方法来保持更新ptrs[3]

class Foo
{
public:
    int X;
    std::shared_ptr<Foo> Other;

    Foo() : X(10) { }
};

int main()
{
    Foo foo;

    std::vector<std::shared_ptr<Foo>> ptrs(10);

    foo.Other = ptrs[3];

    std::shared_ptr<Foo> other = std::shared_ptr<Foo>(new Foo());
    ptrs[3] = other;

    std::cout << foo.Other->X << std::endl; // throws Access violation exception

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:这是我得到的异常,因为它指向null:

Test.exe中0x01219AEF处的第一次机会异常:0xC0000005:访问冲突读取位置0x00000000.Test.exe中0x01219AEF处的未处理异常:0xC0000005:访问冲突读取位置0x00000000.

c++ smart-pointers shared-ptr

1
推荐指数
1
解决办法
652
查看次数

标签 统计

c++ ×1

shared-ptr ×1

smart-pointers ×1