Why can't I see the copy-constructor being called in the case of returning an object from a function in c++? [duplicate]

StackOverflow https://stackoverflow.com/questions/20831960

Question

In the following code ret variable is stack variable, and once foo returns the memory allocated to ret no longer exists. But string is a class, and a copy constructor is called to copy the contents of ret to var. I wanted to test the validity of this using a test code:

class A
{
public:
    A(){ test(); }
    A(const A &){ std::cout << "copy constructor A" <<std::endl; }
    virtual void test(){ std::cout<< "A" <<std::endl;}
    A & operator=(const A &); 
};

A & A::operator=(const A &)
{
    std::cout << "assignment operator A" << std::endl; 
}

A functionA(int a)
{
    A localA;
    return localA;
}

int main()
{
     A a = functionA(2);    
}

what I expected the output to be was:

  A 
  copy constructor A

however the following code outputs the following:

  A

Can someone tell me why this is happening? Thanks!

Was it helpful?

Solution

See http://en.wikipedia.org/wiki/Copy_elision and http://en.wikipedia.org/wiki/Return_value_optimization.

In a sentence, the compiler sees that you will just be copying the value of localA to a (in main), and rather than running a copy operation, it performs an optimization where it just directly writes to a in the function functionA.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top