c++ - auto_ptr.release() 中的段错误

标签 c++ linux segmentation-fault auto-ptr

调用 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 template unique_ptr (20.7.1) provides a better solution. — end note ]

如果您有权访问它,并且有时间/资源来这样做,请考虑切换到较新的智能指针类。

关于c++ - auto_ptr.release() 中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460182/

相关文章:

regex - 用于从变量中提取 UUID/PARTUUID 的 BASH 脚本

c++ - 将 unsigned char 传递给 cout 时出现意外输出

c++ - 使用运算符 [] 时的 std::map 段错误

c++ - vc++ 应用程序中的看门狗

c++ - 适用于 Windows Mobile native 代码的 MVC 框架

c++ - C++ 中变量、方法等的良好命名约定是什么?

c - 我怎样才能用ffmpeg寻求框架X?

c++ - boost 文件系统中的段错误?

c - 包含 glad.h 时出现段错误

c++ - MSVC : a variable with non-static storage duration cannot be used as a non-type argument