Show Lecture.CopyElision as a slide show.
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.
#include "Loud.h" int main() { Loud beta, gamma; }
Loud::Loud() Loud::Loud() Loud::~Loud() Loud::~Loud()
Sure.
#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.
#include "Loud.h" Loud foo() { Loud zeta; return zeta; } int main() { Loud eta(foo()); }
Loud::Loud() Loud::~Loud()
zeta
and eta
, should have been created.
#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.
#include "Loud.h" Loud foo() { Loud iota; return iota; } int main() { Loud kappa(foo()); }
Loud::Loud() Loud::~Loud()
Loud
class.
Loud
).
iota
.
Instead, the ctor in foo()
constructs directly in kappa
.
No copying; it’s built in the right place.
double
?
double *
?
double
?
std::string
?
const std::string &
?
int
?
std::string
?
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!