调用 auto_ptr release 成员时,我在代码的这一点遇到段错误:
try
{
newMod->init(params);
}
catch (const std::exception& e)
{
#ifndef CONFIG_STATIC
dlclose(handle);
#endif
throw std::runtime_error(utils::buildString(
"%s: Error initializing module %s: %s",
DBG_FUNC_NAME, newMod->name().c_str(), e.what()));
}
_modules.insert(std::make_pair(newMod->name(), newMod.release()));
_modules 在哪里
std::map<std::string, IModule*> _modules;
newMod 是
std::auto_ptr<IModule> newMod(0);
稍后用正确的指针值重置。我知道指向 IModule 的指针是有效的,因为我在释放之前调用了 init 成员。
这个:
_modules.insert(std::make_pair(newMod->name(), newMod.get()));
newMod.release();
工作得很好,gdb 是这么说的:
#0 _M_rep (this=0xbfe8e908, __str=...) at /usr/src/debug/gcc-4.5.1-20101208/obj-i586-suse-linux/i586-suse-linux/libstdc++-v3/include/bits/basic_string.h:287
#1 std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (this=0xbfe8e908, __str=...)
at /usr/src/debug/gcc-4.5.1-20101208/obj-i586-suse-linux/i586-suse-linux/libstdc++-v3/include/bits/basic_string.tcc:173
#2 0x0805d76f in sm::core::mod::ModuleManager::loadModule (this=0x8074768, name=..., params=...) at src/core/ModuleManager.cpp:150
#3 0x08056edb in sm::core::Main::start (this=0xbfe8e9e0) at src/core/Main.cpp:82
#4 0x08055131 in main (argc=4, argv=0xbfe8ebf4) at src/core/smmain.cpp:15
它出现段错误的行是:
{ return &((reinterpret_cast<_Rep*> (_M_data()))[-1]); }
知道这可能有什么问题吗?
最佳答案
_modules.insert(std::make_pair(newMod->name(), newMod.release()));
标准未定义函数参数的求值顺序。实现可以在 newMod->name()
之前评估 newMod.release()
,这会使第二次调用无效。
旁注:auto_ptr
在 C++11 中已弃用(草案 n3290 中的附录 D.10):
The class template
auto_ptr
is deprecated. [ Note: The class templateunique_ptr
(20.7.1) provides a better solution. — end note ]
如果您有权访问它,并且有时间/资源来这样做,请考虑切换到较新的智能指针类。
关于c++ - auto_ptr.release() 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460182/