TL;我的代码的DR如下:
server::server(boost::filesystem::path mappath) : mappath(mappath) {
if(boost::filesystem::is_directory(mappath) && boost::filesystem::exists(mappath)) {
// Do some stuff here
} else {
boost::filesystem::create_directory(mappath);
}
}
当mappath
存在时,代码可以工作(几乎没有,因为我发现 Boost 几乎在每个函数中都存在段错误(。
但是,如果没有,它会抛出异常,并显示消息"地址错误"。
当我通过std::cout
打印mappath
时,它返回:
"/home/myusername/.testfolder/huni/ENTER YOUR TEXT HERE"
这是正确的。
请注意,当我尝试在else 语句中打印mappath
时,它会出现段错误。
我推断出is_directory
或exists
中有些东西弄乱了mappath
,因为在if
语句之前打印时没有错误。
我为自己写了一个MCVE。当路径不存在时,提升抛出
terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
what(): boost::filesystem::create_directory: No such file or directory
Aborted (core dumped)
因为程序首先检查路径是否为目录,然后检查路径是否存在(正确(。
当路径存在并且它是一个目录时,程序在没有输出的情况下运行,并且不执行任何操作(正确(。
当路径存在并且是文件时,提升会抛出
terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
what(): boost::filesystem::create_directory: File exists
Aborted (core dumped)
因为它无法创建目录(正确(。
因此,您的代码段会执行它应该执行的操作。也许您应该更改if
语句中的顺序并在else
中添加支票:
#include <boost/filesystem.hpp>
#include <iostream>
class server {
public:
server(boost::filesystem::path mappath) : mappath(mappath) {
if(boost::filesystem::exists(mappath) && boost::filesystem::is_directory(mappath)) {
// Do some stuff here
} else if (!boost::filesystem::exists(mappath)) {
boost::filesystem::create_directory(mappath);
}
}
private:
boost::filesystem::path mappath;
};
int main() {
server s("/path/test");
return 0;
}
现在程序检查路径是否存在。如果路径存在,程序将检查该路径是否为目录。如果路径不存在,则创建目录。
事实证明Bad address
是特定于 POSIX 的错误。
我无法在if
语句的 else 子句中打印mappath
的原因是is_directory
弄乱了引用。
它到底在做什么,我无法弄清楚。
所以,我已经从 Boost 切换到真正有效的东西。