Last active
September 1, 2017 04:12
-
-
Save sakamoto-poteko/5d242513e61f921eed76634c8d24406c to your computer and use it in GitHub Desktop.
std::move in ctor initializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <utility> | |
#include <iostream> | |
class ctor | |
{ | |
public: | |
ctor() | |
{ | |
std::cout << "default ctor" << std::endl; | |
} | |
ctor(const ctor &a) | |
{ | |
std::cout << "copy ctor" << std::endl; | |
} | |
ctor(ctor &&a) | |
{ | |
std::cout << "move ctor" << std::endl; | |
} | |
}; | |
class ctorholder | |
{ | |
public: | |
ctorholder(ctor &&a) : | |
mctor(a) | |
{ | |
// param a is an lvalue here: a named variable is an lvalue. | |
std::cout << "copy init" << std::endl; | |
} | |
ctorholder(ctor &a) : | |
mctor(std::move(a)) | |
{ | |
// This would work | |
std::cout << "move init" << std::endl; | |
} | |
ctor mctor; | |
}; | |
int main() | |
{ | |
ctor a; | |
ctorholder holder1(a); // Correct | |
ctorholder holder2(std::move(a)); // Doesn't work. calls copy ctor | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://stackoverflow.com/questions/13138851/why-do-i-need-to-use-stdmove-in-the-initialization-list-of-a-move-constructor