Move constructor not called?

Hi
I've been trying to learn about move semantics and i thought i finally had a pretty good grasp of it....but nope.

I wrote this program expecting that it would print "constr" and then "move constr" :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

class MyClass
{
  public:
    MyClass()
    {
      std::cout << "constr\n";
    }

    MyClass(const MyClass& rhs)
    {
      std::cout << "copy constr\n";
    }

    MyClass(MyClass&& rhs)
    {
      std::cout << "move constr\n";
    }
};


void test(MyClass&& rref)
{
}


int main()
{
  MyClass a; //invokes contructor 

  test(std::move(a)); //doesn't invoke move constructor ??

  return 0;
}


When i run it, however, it only prints "constr" and nothing else.

Can anyone explain this behavior to me? because to my understanding the std::move function should (through some magic i dont understand yet) convert the lvalue to an rvalue thus invoking the move constructor when being passed to test(), but it doesn't :(
Last edited on
std::move doesn't construct a new object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

class MyClass
{
  public:
    MyClass()
    {
      std::cout << "constr\n";
    }

    MyClass(const MyClass& rhs)
    {
      std::cout << "copy constr\n";
    }

    MyClass(MyClass&& rhs)
    {
      std::cout << "move constr\n";
    }
};


int main()
{
  MyClass a; //invokes contructor 
  MyClass b(a); //invokes copy contructor 
  MyClass c(std::move(a)); // invokes move constructor 

  return 0;
}

You will get a call to MyClass::MyClass(MyClass &&) if you change the definition of test() to this:
1
2
3
void test(MyClass moved)
{
}
Topic archived. No new replies allowed.