Move constructors and inheritance

▼魔方 西西 提交于 2019-11-30 17:28:16

One of the more confusing things about functions taking rvalue references as parameters is that internally they treat their parameters as lvalues. This is to prevent you from moving the parameter before you mean to, but it takes some getting used to. In order to actually move the parameter, you have to call std::move (or std::forward) on it. So you need to define your move constructor as:

T(T&& o): T0(std::move(o)) { puts("move"); }

and your move assignment operator as:

T& operator=(T&& o) { puts("move assign"); return static_cast<T&>(T0::operator=(std::move(o))); }

You're only ever calling your base class's stuff with lvalues:

void foo(int&){}  // A
void foo(int&&){} // B

void example(int&& x)
{
    // while the caller had to use an rvalue expression to pass a value for x,
    // since x now has a name in here it's an lvalue:
    foo(x); // calls variant A
}

example(std::move(myinteger)); // rvalue for us, lvalue for example

That is, you need:

T(T&& o):
T0(std::move(o)) // rvalue derived converts to rvalue base
{
    puts("move");
}

And:

T& operator=(T&& o)
{
    puts("move assign");

    T0::operator=(std::move(o)));

    return *this;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!