Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move constructor called with copy elision?

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;
}
like image 826
newID Avatar asked Jun 13 '26 00:06

newID


1 Answers

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:

  • https://en.cppreference.com/w/cpp/language/copy_elision.html
  • https://devblogs.microsoft.com/cppblog/guaranteed-copy-elision-does-not-elide-copies
like image 183
Amir Roox Avatar answered Jun 15 '26 13:06

Amir Roox