I am trying to construct std::string in-place i.e. within an unsigned char array[sizeof(std::string)]
and then use it later on. Now, while I can definitely reinterpret_cast
the array to std::string
and once initialized, it shows the correct size, printing it to console (using std::cout
) prints a blank string, while std::string::size()
returns the correct size. What could lead to such behavior? My first doubt is I am messing up alignment of the storage somehow?
There is some confusion from how I worded the question. Here is the snippet:
unsigned char array[sizeof(std::string)];
::new (static_cast<void*>(array)) std::string("string");
const auto& str = *reinterpret_cast<std::string*>(array);
std::cout << str.size(); // correctly prints 6
std::cout << str; // prints nothing (no characters get displayed)
This behavior is only displayed on GCC 8.x on Linux, I get the right output on Windows 10 with MSVC 2015.
Aucun commentaire:
Enregistrer un commentaire