Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Constructor? [duplicate]

Tags:

c++

Possible Duplicate:
Why copy constructor is not called in this case?

When you pass an object to a function by value or return an object from a function by value, the copy constructor must be called. However, in some compilers this does not happen? Any explanation?

like image 801
JohnJohn Avatar asked Sep 28 '26 22:09

JohnJohn


2 Answers

I assume they are referring to return-value optimization implemented in many compilers where the code:

CThing DoSomething();

gets turned into

void DoSomething(CThing& thing);

with thing being declared on the stack and passed in to DoSomething:

CThing thing;
DoSomething(thing);

which prevents CThing from needing to be copied.

like image 155
Doug T. Avatar answered Sep 30 '26 10:09

Doug T.


It often doesn't happen because it doesn't need to happen. This is called copy elision. In many cases, the function doesn't need to make copies, so the compiler optimizes them away. For example, with the following function:

big_type foo(big_type bar)
{
  return bar + 1;
}

big_type a = foo(b);

Will get converted to something like:

void foo(const big_type& bar, big_type& out)
{
  out = bar + 1;
}

big_type a;
foo(b, a);

The removal of the return value is called the "Return Value Optimization" (RVO), and is implemented by most compilers, even when optimizations are turned off!

like image 34
Peter Alexander Avatar answered Sep 30 '26 11:09

Peter Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!