I can compute a const char*
presentation of an std::filesystem::path
variable like that:
std::filesystem::path path1(L"ConsoleApplication1.cpp");
std::string strPath1 = path1.string();
const char* charArrPath1 = strPath1.c_str();
But if I omit explicit assignment of a string
variable and use method chaining in a char array initialization statement
const char* charArrPath1 = path1.string().c_str();
variable charArrPath1
contains garbage after execution.
How come the chaining of methods seemingly fails to work?
PS If I explicitly assign the result of string()
on path1
to some unrelated variable after initialization of charArrPath1
, I do have the result as expected:
std::filesystem::path path1(L"ConsoleApplication1.cpp");
const char* charArrPath1 = path1.string().c_str();
std::string strPathUnrelated = path1.string();
std::cout << charArrPath1 << std::endl;
EPILEGOMENON:
The method chaining seems to fail when the code is run in x86 configurations, both Debug and Release. When run in an x64 Release configuration, the following program
#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;
}
prints out
ConsoleApplication1.cpp
Does anyone have an explanation for this behavior?