The copy constructor exists to make copies. In theory when you write a line like:
CLASS c(foo());
The compiler would have to call the copy constructor to copy the return of foo()
into c
.
Copy elision is a technique to skip calling the copy constructor so as not to pay for the overhead.
For example, the compiler can arrange that foo()
will directly construct its return value into c
.
Here's another example. Let's say you have a function:
void doit(CLASS c);
If you call it with an actual argument, the compiler has to invoke the copy constructor so that the original parameter cannot be modified:
CLASS c1;
doit(c1);
But now consider a different example, let's say you call your function like this:
doit(c1 + c1);
operator+
is going to have to create a temporary object (an rvalue). Instead of invoking the copy constructor before calling doit()
, the compiler can pass the temporary that was created by operator+
and pass that to doit()
instead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…