[英]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.