The following code prints "move constructor" with c++11/c++14 with -fno-elide-constructors. However, with c++17/c++20 and -fno-elide-constructors, no "move constructor" prints.
Why is the move constructor called? I thought this was directly created, no? This is very anti-intuitive.
#include <iostream>
struct Data {
Data() {
std::cout << "constructor\n";
};
Data(const Data& d) {
std::cout << "copy constructor \n";
};
Data(Data&& d) {
std::cout << "move constructor \n";
};
};
int main()
{
auto d1 = Data();
return 0;
}
In C++17 this is no longer an "Optimization", but part of the "Language Semantics".
Or, more generally, in C++14 a temporary object is first created and then moved to dl. But in C++17, according to the principle of guaranteed copy elision , the object is created directly in dl. So, in the end, neither a copy nor a move is performed.
Resources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With