Categories
c++ c++-faq copy-elision optimization return-value-optimization

What are copy elision and return value optimization?

474

What is copy elision? What is (named) return value optimization? What do they imply?

In what situations can they occur? What are limitations?

2

  • 2

    Copy elision is one way to look at it; object elision or object fusion (or confusion) is another view.

    Aug 25, 2015 at 23:58

  • 1

    I found this link helpful.

    Mar 2, 2020 at 8:30

320

Introduction

For a technical overview – skip to this answer.

For common cases where copy elision occurs – skip to this answer.

Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. It makes returning by value or pass-by-value feasible in practice (restrictions apply).

It’s the only form of optimization that elides (ha!) the as-if rule – copy elision can be applied even if copying/moving the object has side-effects.

The following example taken from Wikipedia:

struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
};
 
C f() {
  return C();
}
 
int main() {
  std::cout << "Hello World!\n";
  C obj = f();
}

Depending on the compiler & settings, the following outputs are all valid:

Hello World!
A copy was made.
A copy was made.


Hello World!
A copy was made.


Hello World!

This also means fewer objects can be created, so you also can’t rely on a specific number of destructors being called. You shouldn’t have critical logic inside copy/move-constructors or destructors, as you can’t rely on them being called.

If a call to a copy or move constructor is elided, that constructor must still exist and must be accessible. This ensures that copy elision does not allow copying objects which are not normally copyable, e.g. because they have a private or deleted copy/move constructor.

C++17: As of C++17, Copy Elision is guaranteed when an object is returned directly:

struct C {
  C() {}
  C(const C&) { std::cout << "A copy was made.\n"; }
};
 
C f() {
  return C(); //Definitely performs copy elision
}
C g() {
    C c;
    return c; //Maybe performs copy elision
}
 
int main() {
  std::cout << "Hello World!\n";
  C obj = f(); //Copy constructor isn't called
}

16

  • 4

    could you plz explain when is the 2nd output happen and when the 3rd?

    Jun 19, 2014 at 14:00


  • 3

    @zhangxaochen when and how the compiler decides to optimize that way.

    Jun 19, 2014 at 15:11

  • 13

    @zhangxaochen, 1st output: copy 1 is from the return to a temp, and copy 2 from temp to obj; 2nd is when one of the above is optimezed, probably the reutnr copy is elided; the thris both are elided

    – victor

    Nov 7, 2014 at 16:06

  • 4

    Hmm, but in my opinion, this MUST be a feature we can rely on. Because if we can’t, it would severely affect the way we implement our functions in modern C++ (RVO vs std::move). During watching some of the CppCon 2014 videos, i really got the impression that all modern compilers always do RVO. Furthermore, I’ve read somewhere that also without any optimizations on, the compilers apply it. But, of course, I am not sure about it. That’s why I am asking.

    – j00hi

    Feb 5, 2015 at 8:02

  • 9

    @j00hi: Never write move in a return statement – if rvo is not applied, the return value is moved out by default anyway.

    – MikeMB

    Mar 10, 2015 at 1:32

115

Standard reference

For a less technical view & introduction – skip to this answer.

For common cases where copy elision occurs – skip to this answer.

Copy elision is defined in the standard in:

12.8 Copying and moving class objects [class.copy]

as

31) When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class
object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases,
the implementation treats the source and target of the omitted copy/move operation as simply two different
ways of referring to the same object, and the destruction of that object occurs at the later of the times
when the two objects would have been destroyed without the optimization.123 This elision of copy/move
operations, called copy elision, is permitted in the following circumstances (which may be combined to
eliminate multiple copies):

— in a return statement in a function with a class return type, when the expression is the name of a
non-volatile automatic object (other than a function or catch-clause parameter) with the same cvunqualified
type as the function return type, the copy/move operation can be omitted by constructing
the automatic object directly into the function’s return value

— in a throw-expression, when the operand is the name of a non-volatile automatic object (other than a
function or catch-clause parameter) whose scope does not extend beyond the end of the innermost
enclosing try-block (if there is one), the copy/move operation from the operand to the exception
object (15.1) can be omitted by constructing the automatic object directly into the exception object

— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved
to a class object with the same cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the omitted copy/move

— when the exception-declaration of an exception handler (Clause 15) declares an object of the same type
(except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted
by treating the exception-declaration as an alias for the exception object if the meaning of the program
will be unchanged except for the execution of constructors and destructors for the object declared by
the exception-declaration.

123) Because only one object is destroyed instead of two, and one copy/move constructor is not executed, there is still one
object destroyed for each one constructed.

The example given is:

class Thing {
public:
  Thing();
  ~Thing();
  Thing(const Thing&);
};
Thing f() {
  Thing t;
  return t;
}
Thing t2 = f();

and explained:

Here the criteria for elision can be combined to eliminate two calls to the copy constructor of class Thing:
the copying of the local automatic object t into the temporary object for the return value of function f()
and the copying of that temporary object into object t2. Effectively, the construction of the local object t
can be viewed as directly initializing the global object t2, and that object’s destruction will occur at program
exit. Adding a move constructor to Thing has the same effect, but it is the move construction from the
temporary object to t2 that is elided.

4

  • 2

    Is that from the C++17 standard or from an earlier version?

    – Nils

    May 7, 2019 at 12:29

  • 1

    Why can’t function parameter be return value optimized if it’s the same type as function’s return type?

    Jun 20, 2020 at 19:26

  • 1

    This tries to answer – stackoverflow.com/questions/9444485/…

    Jun 20, 2020 at 19:48

  • 3

    Is there any type of copy-elision for primitive types? If I have a function that propagates a return value (maybe an error code), will there be any optimisation similar to objects?

    – WARhead

    Aug 3, 2020 at 12:50

111

Common forms of copy elision

For a technical overview – skip to this answer.

For a less technical view & introduction – skip to this answer.

(Named) Return value optimization is a common form of copy elision. It refers to the situation where an object returned by value from a method has its copy elided. The example set forth in the standard illustrates named return value optimization, since the object is named.

class Thing {
public:
  Thing();
  ~Thing();
  Thing(const Thing&);
};
Thing f() {
  Thing t;
  return t;
}
Thing t2 = f();

Regular return value optimization occurs when a temporary is returned:

class Thing {
public:
  Thing();
  ~Thing();
  Thing(const Thing&);
};
Thing f() {
  return Thing();
}
Thing t2 = f();

Other common places where copy elision takes place is when an object is constructed from a temporary:

class Thing {
public:
  Thing();
  ~Thing();
  Thing(const Thing&);
};
void foo(Thing t);

Thing t2 = Thing();
Thing t3 = Thing(Thing()); // two rounds of elision
foo(Thing()); // parameter constructed from temporary

or when an exception is thrown and caught by value:

struct Thing{
  Thing();
  Thing(const Thing&);
};
 
void foo() {
  Thing c;
  throw c;
}
 
int main() {
  try {
    foo();
  }
  catch(Thing c) {  
  }             
}

Common limitations of copy elision are:

  • multiple return points
  • conditional initialization

Most commercial-grade compilers support copy elision & (N)RVO (depending on optimization settings). C++17 makes many of the above classes of copy elision mandatory.

2

  • 6

    I’d be interested in seeing the “Common limitations” bullet points explained just a little bit… what makes these limiting factors?

    Jan 16, 2013 at 17:54

  • @phonetagger I linked against the msdn article, hope that clears some stuff out.

    Jan 16, 2013 at 19:11