1,105,295 Community Members

Why no copy constructor called after return??

Member Avatar
mahesh113
Newbie Poster
14 posts since Dec 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi,

Please tell me in the following question why no copy constructor is called when fun returns the A object.
While returning b and constructing c, there is no copy constructor called. Why??

#include<iostream>

using namespace std;

class A
{
    public:
    A(){cout <<"Default\n";}
    A(const A&){
                cout<<"copy\n";
    }
    A fun(A a)
        {
             A b; 
            return b;
        }
};

int main()
{
    A a;
    A c = a.fun(a); // Here atleast copy copy constructor should have been called.
    return 0;
}
Member Avatar
sepp2k
Posting Pro in Training
454 posts since Jul 2012
Reputation Points: 286 [?]
Q&As Helped to Solve: 94 [?]
Skill Endorsements: 23 [?]
 
0
 
Member Avatar
mike_2000_17
21st Century Viking
4,063 posts since Jul 2010
Reputation Points: 2,244 [?]
Q&As Helped to Solve: 795 [?]
Skill Endorsements: 72 [?]
Moderator
Featured
Sponsor
 
0
 

This is a case of return-value-optimization (or RVO). This is one of the few cases (with copy elision) where the compiler is allowed to change the behavior of the code (by eliminating calls to copy constructors and destructors) for optimization purposes. In other words, never depend on a specific number of copies being created as part of the critical behavior of your program.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: