cuvidk cuvidk - 10 days ago 5
C++ Question

Copy elision seems to occur even if compiling with -fno-elide-constructors

#include <iostream>

class A {
public:
A() { std::cout << "Constructor" << std::endl; }
A(const A& a) { std::cout << "Copy Constructor" << std::endl; }
A& operator=(const A& a) { std::cout << "Copy = operator" << std::endl; }
A(A&& a) { std::cout << "Move Constructor" << std::endl; }
A& operator=(A&& a) { std::cout << "Move = operator" << std::endl; }
~A() { std::cout << "Destructor" << std::endl; }
};

void f(A&& a) { std::cout << "function" << std::endl; }

int main() {
f(A());
return 0;
}


The output of the following program is:

Constructor
function
Destructor


Why is the move-constructor not called here? It seems like copy elision occurs even if I compile with the flag -fno-elide-constructors:
g++ test.cpp -fno-elide-constructors -std=c++11

Answer

Short answer: You are not move-constructing anything.

You are just creating a temporary Aobject and then passing a reference to it. If you want to see move construction, you could e.g. change the signature of f to

void f(A a)
Comments