我可以像这样计算 std::filesystem::path
变量的 const char*
表示:
std::filesystem::path path1(L"ConsoleApplication1.cpp");
std::string strPath1 = path1.string();
const char* charArrPath1 = strPath1.c_str();
但是如果我省略了对 string
变量的显式赋值并在 char 数组初始化语句中使用方法链接
const char* charArrPath1 = path1.string().c_str();
执行后变量 charArrPath1
包含垃圾。
为什么方法链接似乎不起作用?
PS 如果我在 charArrPath1
初始化后将 path1
上的 string()
的结果显式分配给一些不相关的变量,我确实有结果符合预期:
std::filesystem::path path1(L"ConsoleApplication1.cpp");
const char* charArrPath1 = path1.string().c_str();
std::string strPathUnrelated = path1.string();
std::cout << charArrPath1 << std::endl;
结语:
当代码在 x86 配置(调试和发布)中运行时,方法链接似乎失败。在 x64 发布配置中运行时,以下程序
#include <iostream>
#include <filesystem>
int main()
{
std::filesystem::path path1(L"ConsoleApplication1.cpp");
const char* charArrPath1 = path1.string().c_str();
std::cout << charArrPath1 << std::endl;
}
打印出来
ConsoleApplication1.cpp
有人对此行为有解释吗?
最佳答案
因为 std::filesystem::path::string
按值返回,它返回的是一个temporary ,它将在完整表达式后被销毁,使从 c_str()
获得的指针悬空。
如您所试,如果您使用不会立即销毁的命名变量,指针将不会悬挂。
关于c++ - 为什么语句中的链接方法无法给出预期的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943081/