[英]how to let filesystem::path's c_str() work?
我有個問題:
#include <iostream>
#include <string>
#include <filesystem>
int main()
{
using namespace std;
using namespace filesystem;
path p = current_path();
cout << p << endl;
cout << p.string() << endl;
cout << p.string().c_str() << endl;
cout << p.c_str() << endl;
return 0;
}
output 在這里:
"D:\\VSCodeData\\EffectiveC++"
D:\VSCodeData\EffectiveC++
D:\VSCodeData\EffectiveC++
0x1667248
我不知道為什么第四個不起作用。
另一個問題在這里:
#include <iostream>
#include <string>
#include <filesystem>
int main()
{
using namespace std;
using namespace filesystem;
path p = current_path();
auto sptr = p.string().c_str();
cout << "this is OK: " << p.string().c_str() << endl;
cout << "After operator= : " << sptr << endl;
cout << "convert to const char* :" << (const char *)p.c_str() << endl;
}
output 在這里:
this is OK: D:\VSCodeData\EffectiveC++
After operator= :
convert to const char* :D
我不知道發生了什么。
在 Windows 上path::c_str()
返回wchar_t const*
而不是char const*
。 您可以使用wcout
打印它:
wcout << p.c_str() << '\n';
p.string() 返回一個字符串值,
這個值的生命周期是多少?
auto sptr = p.string().c_str(); // the value returned by p.string() is destructed after this line
所以 sptr 是一個懸空指針,因為它指的是一個被破壞的字符串
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.