Home > Back-end >  how to let filesystem::path's c_str() work?
how to let filesystem::path's c_str() work?

Time:10-03

I have a question:

#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;
}

The output is here:

"D:\\VSCodeData\\EffectiveC  "
D:\VSCodeData\EffectiveC  
D:\VSCodeData\EffectiveC  
0x1667248

I don't know why the fourth doesn't work.

The other question is here:

#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;
}

The output is here:

this is OK: D:\VSCodeData\EffectiveC  
After operator=  :
convert to const char* :D

I don't know what happend.

CodePudding user response:

On Windows path::c_str() returns wchar_t const* and not char const*. You can use wcout to print it:

wcout << p.c_str() << '\n';

CodePudding user response:

p.string() return a string value,

what is the lifetime of this value ?

auto sptr = p.string().c_str(); // the value returned by p.string() is destructed after this line

so sptr is a dangling pointer because it refer to a destructed string

  • Related