shared_ptr的复制分配会导致分段错误吗?

时间:2018-04-06 09:43:39

标签: c++ gcc

我正在使用gcc 5.4进行编译。

通过将std::map<std::string, std::shared_ptr<SpritePack>>存储在SpritePack中,我管理了一些资源make_shared。因此,当我使用void Sprite::setSpritePack(std::shared_ptr<SpritePack> spritePack) { _spritePack = spritePack; } 构造_spritePack时,只要地图存在,引用计数器就应该大于0。在完整的代码中(太大而不能包含这里的所有内容),我可以打印出参考计数器,并看到它在下面显示的代码点为4。

我的问题出现在这里:

std::shared_ptr<SpritePack>

其中Program received signal SIGSEGV, Segmentation fault. 0x0000000000438159 in std::swap<p2d::graphics::SpritePack*> (__a=@0x7ffffffe7430: 0xb16440, __b=@0x140: <error reading variable>) at /usr/include/c++/5/bits/move.h:186 186 __a = _GLIBCXX_MOVE(__b); #0 0x0000000000438159 in std::swap<p2d::graphics::SpritePack*> (__a=@0x7ffffffe7430: 0xb16440, __b=@0x140: <error reading variable>) at /usr/include/c++/5/bits/move.h:186 #1 0x00000000004380ef in std::__shared_ptr<p2d::graphics::SpritePack, (__gnu_cxx::_Lock_policy)2>::swap (this=0x7ffffffe7430, __other=...) at /usr/include/c++/5/bits/shared_ptr_base.h:1076 #2 0x00000000004380a6 in std::__shared_ptr<p2d::graphics::SpritePack, (__gnu_cxx::_Lock_policy)2>::operator=(std::__shared_ptr<p2d::graphics::SpritePack, (__gnu_cxx::_Lock_policy)2>&&) (this=0x140, __r=<unknown type in /path/to/project/build/src/p2d-run, CU 0x1072be, DIE 0x116f51>) at /usr/include/c++/5/bits/shared_ptr_base.h:1000 #3 0x0000000000438042 in std::shared_ptr<p2d::graphics::SpritePack>::operator=(std::shared_ptr<p2d::graphics::SpritePack>&&) (this=0x140, __r=<unknown type in /path/to/project/build/src/p2d-run, CU 0x1072be, DIE 0x116e9b>) at /usr/include/c++/5/bits/shared_ptr.h:294 #4 0x0000000000438010 in p2d::graphics::Sprite::setSpritePack (this=0x0, spritePackArg=std::shared_ptr (empty) 0x0) 是Sprite类的issue类型变量的成员。为什么gcc不允许我复制/分配共享指针?

我已经在我的代码中的各个点仔细检查了shared_ptrs,并且我知道在传递问题的shared_ptr的每个点(按值),它指向相同的内存位置。资源不会在contianer中移动,因为资源是堆分配的,而是我管理指针。

在此分段错误之前也没有调用析构函数。

分配中出现问题,gdb打印出以下回溯:

issue

如果此处缺少信息,我会按要求添加。目前,我没有看到任何其他内容可以进一步添加。

1 个答案:

答案 0 :(得分:5)

在堆栈跟踪中,您会看到:

#4  0x0000000000438010 in p2d::graphics::Sprite::setSpritePack (this=0x0, spritePackArg

表示在具有setSpritePack(this)nullptr对象的对象上调用Sprite

您遇到的问题是这样的分配。这是您尝试分配给不存在的(nullptr)对象的成员变量。

您应该在调用Sprite时调查nullptr对象为setSpritePack的原因 - 这就是您的错误所在。