我试图通过派生类移动ctor显式调用基类移动ctor但惊喜!,这实际上是调用基类复制ctor不是基类移动ctor。为什么基础移动构造函数的显式调用实际上调用基础构造函数?
我在对象上使用std::move()
函数以确保派生的move ctor被调用!
代码:
class Base
{
public:
Base(const Base& rhs){ cout << "base copy ctor" << endl; }
Base(Base&& rhs){ cout << "base move ctor" << endl; }
};
class Derived : public Base
{
public:
Derived(Derived&& rhs) : Base(rhs) { cout << "derived move ctor"; }
Derived(const Derived& rhs) : Base(rhs) { cout << "derived copy ctor" << endl; }
};
int main()
{
Derived a;
Derived y = std::move(a); // invoke move ctor
cin.ignore();
return 0;
}
程序输出:
基地拷贝构造函数
衍生举动男星
正如你看到的,基类移动男星正在被遗忘,所以我怎么称呼它?
以及如果我会在主函数中写这个:Derived y = Derived();也忘记了std :: move?我已经尝试过,在那种情况下,我没有任何程序输出,那么真正被称为什么? – codekiddy
@codekiddy:在示例中,Derived y = Derived()概念上称为移动构造函数:右侧的对象不能被引用,即它不是左值。但是,移动构造可能被大多数编译器忽略:如果编译器可以直接在正确的位置构建临时对象,则可以不使用移动(或复制)构造,即使构造函数不会产生副作用, t被忽略(例如,从构造函数或析构函数中输出)。 –
所以移动rhs的基础部分我被迫在派生的移动ctor中使用Base(std :: move(rhs)),有没有什么办法可以避免std :: move?多谢 – codekiddy