cuvidk cuvidk - 1 year ago 108
C++ Question

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

#include <iostream>

class A {
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() {
return 0;

The output of the following program is:


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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download