Issue
both gcc and clang version is 11, here is the sample code
#include <string>
#include <cstddef>
void store_rvalue_string(std::byte* buffer, std::string&& value) {
*reinterpret_cast<std::string*>(buffer) = std::move(value);
}
int main() {
auto buffer = new std::byte[1024];
std::string str = "hello";
store_rvalue_string(buffer, std::move(str));
}
Solution
This is a strict aliasing violation, and thus UB.
A less formal answer is that you're calling std::basic_string::operator=
on a piece of memory for which the string
constructor was never called in the first place.
My guess is that on Clang the memory happened to be filled with zeroes, and that a string filled with zero bytes counts as empty on your standard library implementation.
The right solution is to use placement-new, to create a new object (by calling its constructor):
new(buffer) std::string(std::move(str));
Answered By - HolyBlackCat