繁体   English   中英

默认分配 std::set 的段错误<void*></void*>

[英]Seg fault with default allocation std::set<void*>

我正在尝试学习 STL void* 分配器。 这是我的代码

#include <set>
#include <memory>

class Test {
 public:
    std::set<void*> GetAllInformation() { return info_set_; }

 private:
    std::set<void*> info_set_;
};

int main() {
    std::unique_ptr<Test> test_obj_;

    const auto info = test_obj_->GetAllInformation();
    if (info.empty())
        std::cout << "info empty";

    return 0;
}

但是我在

线程 1 收到信号 SIGSEGV,分段错误。

0x00402a18 in std::_Rb_tree<void*, void*, std::_Identity<void*>, std::less<void*>, std::allocator<void*> >::_M_root (this=0x0) at C :/程序文件(x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/lib/gcc/i686-w64-mingw32/8.1.0/include/c++/bits/stl_tree。高:733

stl_tree.h

      _Const_Base_ptr
      _M_root() const _GLIBCXX_NOEXCEPT
      { return this->_M_impl._M_header._M_parent; }

谁能帮忙解释一下? 谢谢

问题是当前test_obj_未指向任何Test object。因此表达式test_obj_->GetAllInformation()导致未定义的行为

未定义的行为意味着任何事情1都可能发生,包括但不限于给出您预期的 output 的程序。但永远不要依赖(或根据)具有未定义行为的程序的 output。

因此,您看到(可能看到)的 output 是未定义行为的结果。 正如我所说,不要依赖具有 UB 的程序的 output 该程序可能会崩溃(这就是您的情况)。

例如,这里程序没有崩溃,但在这里它崩溃了。

因此,使程序正确的第一步是删除 UB。 只有这样你才能开始对程序的 output 进行推理。


1有关未定义行为的更技术准确的定义,请参阅此处提到的内容: There are no restrictions on the behavior of the program

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM