CS253: Software Development with C++

Fall 2020

Copy Elision

Show Lecture.CopyElision as a slide show.

CS253 Copy Elision

I don’t have the foggiest idea who could possibly be missing from this picture.

The Loud Class

The following examples use our class Loud, which displays a message for every method invoked.

int main() {
    Loud alpha;
}
Loud::Loud()
Loud::~Loud()

No surprise, here. alpha got created & destroyed.

More Construction

int main() {
    Loud beta, gamma;
}
Loud::Loud()
Loud::Loud()
Loud::~Loud()
Loud::~Loud()

Sure.

Copy ctor & assignment

int main() {
    Loud delta;
    Loud epsilon(delta);
    delta=epsilon;
}
Loud::Loud()
Loud::Loud(const Loud &)
Loud::operator=(const Loud &)
Loud::~Loud()
Loud::~Loud()

As expected.

More copying

Loud foo() {
    Loud zeta;
    return zeta;
}

int main() {
    Loud eta(foo());
}
Loud::Loud()
Loud::~Loud()

Ludicrous copying

int main() {
    Loud theta = Loud(Loud(Loud(Loud(Loud(Loud(Loud(Loud())))))));
}
Loud::Loud()
Loud::~Loud()

There should be more than that.

Elision

Loud foo() {
    Loud iota;
    return iota;
}

int main() {
    Loud kappa(foo());
}
Loud::Loud()
Loud::~Loud()

Parameter Passing

No Answers Yet

X86 Answers

On the popular X86-64 CPU architecture:

Parameter Passing

When a function returns an non-scalar object, compilers typically pass a hidden argument to the result.

// User code:
string tv() {
   string s="SNL";
   return s;
}

int main() {
   string fav=tv();


   cout << fav;
}
SNL
// Implementation:
void tv(string &out) {
   string s="SNL";
   out=s;
}

int main() {
   string result;
   tv(result);
   string fav=result;
   cout << fav;
}
SNL
// After optimization:
void tv(string &out) {
   out="SNL";

}

int main() {
   string fav;
   tv(fav);

   cout << fav;
}
SNL

All thanks to copy elision !