dimanche 11 septembre 2022

C++11: passing a temp object to a ctor, doesn't call move constructor, why? [duplicate]

I was trying to see why move constructor is called, as below:

#include<iostream>
#include<utility>
using namespace std;
struct M{
  M(){cout<<"ctor\n";}
  M(const M&m){cout<<"copy ctor\n";}
  M(M&&m){cout<<"move ctor\n";}
  M& operator=(const M&m){cout<<"copy operator=\n"; return *this;}
  M& operator=(M&&m){cout<<"move operator=\n"; return *this;}
};
int main(){
  M obj1(M{}); // why this prints "ctor", but not "move ctor"?
  cout << "----\n";
  M obj2(move(M{})); // ctor and move ctor, as expected.
  return 0;
}

compile with clang++-14 and msvc-2022, both gave same result:

ctor
----
ctor
move ctor

My question lies in M obj1(M{}): as long as M{} is a temporary object, it's right value, so I expected that move ctor will be called. But in fact not.

Only when I explicitly called M obj2(move(M{}));, this time, ctor + move ctor being called.

So M{} is an r-value, move(M{}) returns an r-value, why they gave different result on object construction?

Thanks!

Aucun commentaire:

Enregistrer un commentaire