Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor using auto on the left side [duplicate]

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

In what situations can they occur? What are limitations?

  • If you were referenced to this question, you're probably looking for the introduction.
  • For a technical overview, see the standard reference.
  • See common cases here.
like image 583
Luchian Grigore Avatar asked Nov 22 '22 07:11

Luchian Grigore


1 Answers

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.

like image 149
Luchian Grigore Avatar answered Nov 24 '22 21:11

Luchian Grigore