Prev: How can I alter how a user-defined type/enum is displayed? (facet/locale?)
Next: basic_string CoW concurrency: typo in N2668, or very subtle point?
From: aejeet on 2 Jul 2010 06:16 Hi, The following code samples must give the same output but are giving different output. class A{ public: A(){} A(const A&){cout<<"Copying myself"<<endl;} }; A func(A a) { return a; } int main() { A a; func(a); } output: Copying myself Copying myself ********************** class A{ public: A(){} A(const A&){cout<<"Copying myself"<<endl;} }; A func(A a) { A obj; return obj; } int main() { A a; func(a); } output: Copying myself DOUBT: In the second sample why is the copy constructor not being called while returning the value ? -Aejeet -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Peter C. Chapin on 2 Jul 2010 09:34
On 2010-07-02 17:16, aejeet wrote: > DOUBT: In the second sample why is the copy constructor not being > called while returning the value ? This is most likely due to the "return value optimization." The local object is actually constructed in the caller's address space where the return value is going to ultimately be placed. Thus there is no need to copy it when the function returns. If you Google for "RVO" or similar things, you should find a lot about it. Peter -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |