C++11: 'decltype class instance declaration' with std::move( ) doesn't call 'move constructor.' Why?

  • A+
Category:Languages

I recently started using c++ and I chose to learn c++11 features. But how c++ codes run is sometimes not so tangible.

below is my code. At the part with "decltype(std::move(sample)) sample2 = std::move(sample);" I'm not sure why this line doesn't call move constructor. Could you explain why?

#include <iostream>  class AAA {    public:       AAA() { std::cout << "default constructor" << std::endl; }       AAA(const AAA& cs) { std::cout << "copy constructor" << std::endl; }       AAA(AAA&& cs) { std::cout << "move constructor" << std::endl; }       ~AAA() { std::cout << "destructor" << std::endl; } };  int main(int argc, char* args[]) {     AAA sample; // ((right here))     decltype(std::move(sample)) sample2 = std::move(sample);      return 0; } 

It is compiled on [ ubuntu 16.04 LTS ] with [ gcc 5.4.0 ]

original code : https://ide.geeksforgeeks.org/tALvLuSNbN

 


Your snippet expands to

AAA&& sample2 = std::move(sample); 

which binds an rvalue (the result of std::move(sample)) to an rvalue reference (sample2). No new object is constructed, and hence no such constructor is called.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: