[英]Copy assignment of shared_ptr causes segmentation fault?
我正在使用gcc 5.4进行编译。
我有一些资源SpritePack
,可以通过将std::shared_ptr<SpritePack>
存储在std::map<std::string, std::shared_ptr<SpritePack>>
。 因此,当我使用make_shared
构造SpritePack
时,只要映射存在,引用计数器就应大于0。 在完整的代码中(太大了,无法在此处包含所有内容),我可以打印出参考计数器,并在下面显示的代码点看到它位于4。
我的问题发生在这里:
void Sprite::setSpritePack(std::shared_ptr<SpritePack> spritePack) {
_spritePack = spritePack;
}
其中_spritePack
是Sprite类的std::shared_ptr<SpritePack>
变量类型的成员。 为什么gcc不允许我复制/分配共享指针?
我在代码的各个点仔细检查了shared_ptrs,并确定在所讨论的shared_ptr传递的每个点(按值)都指向相同的内存位置。 资源也不会在容器中移动,因为资源是堆分配的,而我管理指针。
在此分段错误之前,也不会调用析构函数。
在分配中发生问题,并且gdb打印出以下回溯:
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)
如果此处缺少信息,我将按要求添加。 目前,我看不到其他要补充的内容。
在stacktrace中,您显示的是:
#4 0x0000000000438010 in p2d::graphics::Sprite::setSpritePack (this=0x0, spritePackArg
这表示正在使用nullptr
(此) Sprite
对象的对象上调用setSpritePack
。
您遇到的问题不是这样的分配。 这是您试图分配给不存在的( nullptr
)对象的成员变量。
您应该调查在调用setSpritePack
时Sprite
对象为何为nullptr
的原因-这就是您的错误所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.