c++ - How to get the move constructor calling deliberately -


this question has answer here:

consider following code:

class base { public:     int bi;     base() : bi(100)    {std::cout << "\nbase default constructor ...";}     base(int i) : bi(i) {std::cout << "\nbase int constructor: "<< bi;}     base(const base& b) {std::cout << "\nbase copy constructor";}     base(base&& b)      {std::cout << "\nbase move constructor";} };  base getbase() {     cout << "\nin getbase()";     return base();   } int main() {     base b2(getbase());       base b3 = base(2);        base b4 = getbase();  } 

in spite of rvalues being given, none of above constructions in main calling move constructor. there way ensure user defined move constructor called?

here getting:

in getbase()     base default constructor ... base int constructor: 2 in getbase() base default constructor ... base destructor: 100 base destructor: 2 base destructor: 100 

you can use std::move() method:

base b4 = std::move(getbase()); 

this ensures move constructor called, in line prevents copy-elision optimalize copy constructor out of there. there no need call constructor, more example how not use std::move().


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -