C++ move constructor not called for rvalue reference -


class myclass {   public:       myclass()       {           std::cout << "default constructor\n";       }       myclass(myclass& a)       {           std::cout << "copy constructor\n";       }        myclass(myclass&& b)       {           std::cout << "move constructor\n";       }  };    void test(myclass&& temp) {     myclass a(myclass{}); // calls move constructor expected     myclass b(temp); // calls copy constructor... not expected...?  }  int main() {     test(myclass{});     return 0; } 

for above code, expected both object creations in test() call move constructor because b r-value reference type (myclass&&).

however, passing b myclasss constructor not call move constructor expected, calls copy constructor instead.

why second case calls copy constructor if passed argument of type myclass&& (r-value reference)???

i using gcc 5.2.1. reproduce results, must pass -fno-elide-constructors option gcc disable copy elision optimization.


void test(myclass&& temp) {     if (std::is_rvalue_reference<decltype(temp)>::value)         std::cout << "temp rvalue reference!!\n";     else        std::cout << "temp not rvalue!!\n"; } 

above code prints out "temp rvalue reference" if temp named.

temp's type rvalue reference type.

void test(myclass&& temp) {     myclass a(myclass{}); // calls move constructor expected     myclass b(temp); // calls copy constructor... not expected...?  } 

that because, temp (since has name,) lvalue reference rvalue. treat rvalue @ point, call on std::move

void test(myclass&& temp) {     myclass a(myclass{}); // calls move constructor expected     myclass b(std::move(temp)); // calls move constructor... :-)  } 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -