-4
#include <iostream>
using namespace std;

template <typename T> class tt
{
    public :
    int data;
    tt()
    {
        std::cout << std::endl << "   CONSTRUCTOR" << std::endl;
    }
    tt(const tt & that)
    {
        std::cout << std::endl << "    COPY CONSTRUCTOR" << std::endl;
    }
};


tt<int> test(void)
{
    std::cout << std::endl << "      INSIDE " << std::endl; tt<int> a; a.data =10 ;return a;
}

int main() {
    // your code goes her
    //tt<int> b;
    tt<int> a =test();
    cout<<a.data; //so that return value optimisation doesn't take place
    return 0;
}

Why is the copy constructor not getting called in this case?

It gets called in the following case though

tt<int> b;
tt<int> a =b;

code link : http://ideone.com/e9lq3C

edit : This is not duplicate of What are copy elision and return value optimization?, because returned value is being referenced inside code.

Community
  • 1
  • 1
q126y
  • 1,589
  • 4
  • 18
  • 50

2 Answers2

2

a does not have a different location to the temporary. That is what copy elision and return value optimization do... they make it so that you don't get a temporary. Where you say a in test(), the optimization means you are referring to the same location as a in main. So no copy is required.

jpo38
  • 20,821
  • 10
  • 70
  • 151
Scott Langham
  • 58,735
  • 39
  • 131
  • 204
1

This is all due to compiler optimization (at least RVO). Compilers ends up creating one and only one object her (the one you asked to be created locally in test() becomes the same object as your a variable).

jpo38
  • 20,821
  • 10
  • 70
  • 151