CS253: Software Development with C++

Spring 2019

Copy Elision

Show Lecture.CopyElision as a slide show.

CS253 Copy Elision

The Loud Class

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

#include "Loud.h"

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

No surprise, here. alpha got created & destroyed.

More Construction

#include "Loud.h"

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

Sure.

Copy ctor & assignment

#include "Loud.h"

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

#include "Loud.h"

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

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

Ludicrous copying

#include "Loud.h"

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

There should be more than that.

Elision

#include "Loud.h"
Loud foo() {
    Loud iota;
    return iota;
}

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

Parameter Passing

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!

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2019-05-13T14:49

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building