为什么使用已删除的右值引用构造函数?

why use of deleted rvalue reference constructor function?

本文关键字:引用 构造函数 删除 为什么      更新时间:2023-10-16

这是一个非常简单的例子,包括类A和B。 我只想允许深层复制,所以我禁用了右值引用构造函数。

#include <iostream>
class B;
class A {
public:
A();
~A();
A(const A & other);
A& operator=(const A & other);
A(A && ) = delete;
A& operator=(A && ) = delete;
B toB() const;
private:
int a_;
};
class B {
public:
B();
~B();
B(const B & other);
B& operator=(const B & other);
B(B && ) = delete;
B& operator=(B && ) = delete;
A toA() const;
private:
int b_;
};
A::A()
{
}
A::~A()
{
}
A::A(const A & other)
: a_(other.a_)
{
}
A& A::operator=(const A & other)
{
a_ = other.a_;
return *this;
}
B A::toB() const
{
return B();
}
B::B()
{
}
B::~B()
{
}
B::B(const B & other)
: b_(other.b_)
{
}
B& B::operator=(const B & other)
{
b_ = other.b_;
return *this;
}
A B::toA() const
{
return A();
}

int main()
{
A a();
B b();
return 0;
}

GCC 编译器报告的错误如下:

In member function 'B A::toB() const':
error: use of deleted function 'B::B(B&&)'
return B();
^
note: declared here
B(B && ) = delete;

我在徘徊为什么它使用B(B && )函数,而不是B(const B &)函数。

因为你添加了移动构造函数。已删除但声明的函数仍然是类接口的一部分。这意味着编译器会考虑它,但由于它被标记为已删除,因此会出现错误。如果要强制调用复制构造函数,请删除移动构造函数声明。


从这个删除的函数参考:

任何对已删除函数的使用都是格式不正确的(程序将无法编译)。这包括显式调用(使用函数调用运算符)和隐式调用(调用已删除的重载运算符、特殊成员函数......

[强调我的]

由于删除的函数是接口的一部分,编译器将尝试使用它们。因此,当有一个已删除的移动构造函数时,编译器将看到它并尝试使用它,但由于它被删除,因此会出现错误。

由于如果存在显式复制构造函数(根据此移动构造函数引用),编译器不会创建移动构造函数,因此仅具有默认的复制构造函数将禁止对象的移动。

所有这些都意味着您的课程可以大大简化:

class A {
public:
A() : a_() {}
A(const A & other) = default;
B toB() const;
private:
int a_;
};
class B {
public:
B() : b_() {}
B(const B & other) = default;
A toA() const;
private:
int b_;
};

由于上面的类具有用户声明的复制构造函数,因此不会创建移动构造函数,并且只能复制该类。

每当创建无名称对象时都会调用移动构造函数。

B A::toB() const函数中有一个语句return B();该语句创建一个要从函数返回的无名称对象。要创建无名称对象移动构造函数,需要将其删除。