Created
September 11, 2018 03:04
-
-
Save kenichi-fukushima/197238e0cd23b82666a27abfa5fbd540 to your computer and use it in GitHub Desktop.
No copy on returning a local variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another way to verify there is no copy happening on return is to get addresses of
c
infun()
ande
in main()`. They have the same address.