Skip to content

Instantly share code, notes, and snippets.

@kenichi-fukushima
Created September 11, 2018 03:04
Show Gist options
  • Save kenichi-fukushima/197238e0cd23b82666a27abfa5fbd540 to your computer and use it in GitHub Desktop.
Save kenichi-fukushima/197238e0cd23b82666a27abfa5fbd540 to your computer and use it in GitHub Desktop.
No copy on returning a local variable
// How to run it:
// $ g++ --std=c++11 ~/return_value_optimization.cpp && ./a.out
//
// Output is
// copying obj1
// obj2 is not copied.
#include <iostream>
#include <string>
class MyClass {
public:
MyClass(std::string label)
: label_(label) {}
MyClass(const MyClass& rhs)
: label_(rhs.label_) {
std::cout << "copying " << label_ << "\n";
}
private:
std::string label_;
};
MyClass fun() {
MyClass c("obj2");
return c;
}
int main() {
MyClass c("obj1");
MyClass d = c;
MyClass e = fun();
return 0;
}
@kenichi-fukushima
Copy link
Author

Another way to verify there is no copy happening on return is to get addresses of c in fun() and e in main()`. They have the same address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment