Skip to content

Instantly share code, notes, and snippets.

@sakamoto-poteko
Last active September 1, 2017 04:12
Show Gist options
  • Save sakamoto-poteko/5d242513e61f921eed76634c8d24406c to your computer and use it in GitHub Desktop.
Save sakamoto-poteko/5d242513e61f921eed76634c8d24406c to your computer and use it in GitHub Desktop.
std::move in ctor initializer
#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;
}
@sakamoto-poteko
Copy link
Author

sakamoto-poteko commented Sep 1, 2017

image
From std::vector.
We did it correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment