0

Trying to figure out how does c++11 move constructor work I wrote this code:

#include <iostream>

class Test
{
public:
    Test() { std::cout << "Test() called" << std::endl; a = 1; }
    Test(const Test& other) { std::cout << "Copy ctor called" << std::endl; a = other.a; }
    Test(Test&& other) { std::cout << "Move ctor called" << std::endl; a = other.a; }
    virtual ~Test() {}
    int a;
};

Test smth()
{
    Test result;
    result.a = 5;
    return result;
}

int main()
{
    Test tst(smth());
    std::cout << "val is: " << tst.a << std::endl;
    return 0;
}

When I run it I get the following results:

./move
Test() called
val is: 5

But I expected that output will contain "Move ctor called". Also the value of 'a' was set to 5. That means that some work was done implicitly. Why was my move constructor skipped?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
serggp
  • 31
  • 4

0 Answers0