1

I am trying to understand when the move constructor is called, and wrote this simple piece of code:

class myClass
{
public:
    myClass(int value)
    {
        cout << "This is my constructor" << endl;
    }
    myClass(const myClass& other)
    {
        cout << "This is my copy constructor" << endl;
    }
    myClass(myClass&& other)
    {
        cout << "This is my move constructor" << endl;
    }
};

int main()
{
    myClass a(myClass(3));
}

The output is:

This is my constructor

I understand the constructor is called for myClass(3). My question is, why isn't the move (or even copy) constructor called for moving the memory to 'a'?

Pang
  • 9,564
  • 146
  • 81
  • 122
redDevil
  • 21
  • 1
  • 1
    The compiler recognizes that it isn't needed; you create a new temporary instance with integer parameter 3, and assign it directly to a variable. The compiler eliminated the unnecessary overhead and created a as though it was built with a parameter of 3. The same result would be attained with myClass a = myClass(3); – Matt Jordan Apr 03 '16 at 04:50
  • 1
    Try compiling with -o0 – awiebe Apr 03 '16 at 04:50
  • 2
    You may find [**this page**](http://en.cppreference.com/w/cpp/language/copy_elision) interesting. – WhozCraig Apr 03 '16 at 04:53

0 Answers0