0

I read about copy elision and how it can fasten up Programms by giving possibilities to write code more straight foreword without thinking about references of variables. In a small example I tried to find the limits of this technique.

#include <iostream>

class A
{
public:
   A(){}
   A(const A &a) {std::cout << "Copy" << std::endl;}
};

A foo(A a)
{
   return a;
}

int main(void)
{
   A a = foo(foo(A()));
   std::cout << std::endl;
   A b;
   b = foo(foo(b));

   return 0;
}

https://godbolt.org/z/xo88jq

Output:

Copy
Copy

Copy
Copy
Copy

The compiler already elides many of the copies in this example. But why is the compiler not able to elide all those copies leading to a or in the modification of b?

Marek R
  • 32,568
  • 6
  • 55
  • 140
heitho
  • 61
  • 1
  • 7
  • 1
    This code can't compile. What compiler and version are you using? – NathanOliver Jan 12 '21 at 14:28
  • Because adding the copy constructor disables the opportunity for moving. (You also must have set some kind of record in errors per line of code.) – molbdnilo Jan 12 '21 at 14:35
  • 1
    Depends on what version of C++ your compiler supports. In older standards, copy (or temporary) elision was permitted but not required by the standard in most circumstances - so there was variation between compilers in which cases temporaries would be elided (or not). In C++17, elision became mandatory in quite a few cases, but there are still cases where it is not mandatory (hence, in those cases, there is still variation between compilers). In cases where it is not mandatory, it comes down to "quality of implementation" and may be affected by optimisation settings. – Peter Jan 12 '21 at 14:36
  • 1
    Copy elision's guarantees and non-guarantees have a lot of technical reasons for them, which are driven by common fundamental design principles of operating systems. C++ can't mandate copy elision in a way that simply cannot be implemented. – Sam Varshavchik Jan 12 '21 at 14:40
  • https://godbolt.org/z/39qneb this may help: https://stackoverflow.com/a/50834616/1387438 – Marek R Jan 12 '21 at 14:46

0 Answers0