如何将std::filesystem::path类型转换为const char*类型?
关于std::filesystem::path转const char*的问题解答
是可以转换的,需要根据你使用的操作系统和C++版本选择适配的方案,同时要注意生命周期安全问题:
不同系统的转换方案
- 类Unix系统(Linux/macOS等)
这类系统下std::filesystem::path的底层默认存储字符类型为char,直接调用c_str()方法即可得到const char*类型的结果:const char* path_ptr = outfilename.c_str(); - Windows系统
Windows下path的底层默认存储字符类型为wchar_t,直接调用c_str()返回的是const wchar_t*,无法直接作为const char*参数传入,需要先转成std::string再取指针:
如果需要传入UTF-8编码的路径,C++17及以上可以使用std::string path_str = outfilename.string(); const char* path_ptr = path_str.c_str();u8string()方法:// C++17版本u8string返回std::string std::string utf8_path = outfilename.u8string(); const char* utf8_ptr = utf8_path.c_str(); // C++20及以上版本u8string返回std::u8string,需要做指针转换 std::u8string utf8_path = outfilename.u8string(); const char* utf8_ptr = reinterpret_cast<const char*>(utf8_path.c_str());
关键注意事项
所有从
c_str()拿到的指针生命周期都和对应的宿主对象绑定:指针仅在path对象或者你转换得到的std::string/std::u8string对象存活时有效,绝对不允许写类似const char* p = outfilename.string().c_str()的代码,临时字符串对象销毁后拿到的就是野指针,访问会触发未定义行为。
内容的提问来源于stack exchange,提问作者Techflash
相关产品推荐
相关产品推荐

