Skip to content

Instantly share code, notes, and snippets.

@Shaun289
Created January 16, 2023 07:01
Show Gist options
  • Save Shaun289/069580ce2a3a9b097789337012ed9ebd to your computer and use it in GitHub Desktop.
Save Shaun289/069580ce2a3a9b097789337012ed9ebd to your computer and use it in GitHub Desktop.
Return value optimization
#include <iostream>
class C
{
private:
int _data;
public:
C(int data) {
_data = data;
std::cout << "constructor" << std::endl;
}
C(const C& rhs) {
_data = rhs.data();
std::cout << "copy constructor" << std::endl;
}
int data() const { return _data; }
void setData(int data) { _data = data; }
};
C returnC1()
{
C c1(0);
c1.setData(1);
return c1;
}
int main(int argc, char* argv[])
{
/* constructor
c1=1
*/
C c1 = returnC1();
std::cout << "c1=" << c1.data() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment