1

Possible Duplicate:
What are copy elision and return value optimization?
why isn’t the copy constructor called

Why in the following code both gcc and clang don't call copy constructor of A class even one time (there is only one object created as destructor is called only one time).

class A
{
public:
  explicit A()
  {
    std::cout << "A()" << std::endl;
  }
  A(const A& toCp)
  {
    std::cout << "A(const A&)" << std::endl;
  }
  ~A()
  {
    std::cout << "~A()" << std::endl;
  }
  A& operator=(const A& toCp)
  {
    std::cout << "A::operator=" << std::endl;
  }
};

A fun()
{
  A x;
  std::cout << "fun" << std::endl;
  return x;
}

int main()
{
  A u = fun();
  return 0;
}

Printout of this code is:

A()
fun
~A()

I thought it copy constructor should be called 2 times (one for returning value and one in line A u = fun(7);

I used gcc and clang with -O0 for this code.

Any ideas?

Community
  • 1
  • 1
Yester
  • 652
  • 6
  • 18
  • 4
    [Copy elision](http://en.wikipedia.org/wiki/Copy_elision) try passing `-fno-elide-constructors` to GCC. – Joe Jan 04 '13 at 13:55

1 Answers1

2

The compiler uses copy elision to avoid a copy (or move) for the return value of function fun(). This is a standard and trivial optimization which will almost always be invoked (depending on the compiler and its optimisation settings). The compiler may do this even if the elided copy (or move) constructor would have had side effects (as in your case, where it writes to stdout).

note Copy elision is not restricted to inline functions, but will be used even if the function definition lives in a different compilation unit.

Walter
  • 44,150
  • 20
  • 113
  • 196