这是我的代码:
#include <iostream>
#include <filesystem>
int main(int argc, char *argv[]) {
auto iter = std::filesystem::directory_iterator("foo");
for (auto &entry : iter) {
std::cout << entry.path();
}
}
当我运行它并且目录foo
存在时,我得到了SIGSEGV。所以我开始了gdb:
(gdb) run
Starting program: /home/krausefx/a.out
Program received signal SIGSEGV, Segmentation fault.
0x0000555555556a87 in std::vector<std::filesystem::__cxx11::path::_Cmpt, std::allocator<std::filesystem::__cxx11::path::_Cmpt> >::~vector (
this=0x23) at /usr/include/c++/8/bits/stl_vector.h:567
567 std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish,
(gdb) backtrace
#0 0x0000555555556a87 in std::vector<std::filesystem::__cxx11::path::_Cmpt, std::allocator<std::filesystem::__cxx11::path::_Cmpt> >::~vector (
this=0x23) at /usr/include/c++/8/bits/stl_vector.h:567
#1 0x00005555555566aa in std::filesystem::__cxx11::path::~path (this=0x3) at /usr/include/c++/8/bits/fs_path.h:208
#2 0x0000555555557ebe in std::filesystem::__cxx11::path::_Cmpt::~_Cmpt (this=<incomplete type>) at /usr/include/c++/8/bits/fs_path.h:643
#3 0x0000555555557ed9 in std::_Destroy<std::filesystem::__cxx11::path::_Cmpt> (__pointer=0x3) at /usr/include/c++/8/bits/stl_construct.h:98
#4 0x0000555555557ced in std::_Destroy_aux<false>::__destroy<std::filesystem::__cxx11::path::_Cmpt*> (__first=0x3, __last=0x0)
at /usr/include/c++/8/bits/stl_construct.h:108
#5 0x00005555555576de in std::_Destroy<std::filesystem::__cxx11::path::_Cmpt*> (__first=0x3, __last=0x0)
at /usr/include/c++/8/bits/stl_construct.h:137
#6 0x0000555555556fb9 in std::_Destroy<std::filesystem::__cxx11::path::_Cmpt*, std::filesystem::__cxx11::path::_Cmpt> (__first=0x3, __last=0x0)
at /usr/include/c++/8/bits/stl_construct.h:206
#7 0x0000555555556a9d in std::vector<std::filesystem::__cxx11::path::_Cmpt, std::allocator<std::filesystem::__cxx11::path::_Cmpt> >::~vector (
this=0x7fffffffdcf0) at /usr/include/c++/8/bits/stl_vector.h:567
#8 0x00005555555566aa in std::filesystem::__cxx11::path::~path (this=0x7fffffffdcd0) at /usr/include/c++/8/bits/fs_path.h:208
#9 0x000055555555630d in main (argc=32767, argv=0x7ffff7fadf40 <std::wcout>) at test.cpp:5
(gdb) p this
$1 = (vector * const) 0x23
因此,显然,在初始化directory_iterator
时,出于某种原因调用std::filesystem::path
的析构函数,并且在其中的某个位置,在{{1}上调用std::vector
的析构函数} this
的值,这显然是一件坏事,并导致了SIGSEGV。
这是怎么回事?难道我做错了什么?这是一个编译器错误(编译器是g ++ 8.3.0)吗?
答案 0 :(得分:1)
我不认为std :: filesystem是稳定的。它在我的项目中引起了段错误和其他问题(特别是msys2附带的mingw-w64中的std :: filesystem :: path)。尝试更新您的gcc软件包,然后检查问题是否仍然存在。如果可以,那么您可以提交错误报告,或者只是等待并希望有人已经报告了该错误(在我的情况下,更新解决了该问题)。
答案 1 :(得分:1)
我检查了directory_iterator
在Ubuntu下使用GCC 8可以正常工作。
请确保在编译时添加链接器标志-lstdc++fs
。
如果编译没有成功结束,但至少在我的系统中,编译开始时会遇到段错误。