其他分享
首页 > 其他分享> > c – delete / default关键字是否将相应的方法标记为用户定义?

c – delete / default关键字是否将相应的方法标记为用户定义?

作者:互联网

我有以下代码:

#include <iostream>

class B{
public:
    //this should all be generated by default but
    //throwing them in here just to be sure
    B() = default;
    B(const B& b) = default;
    B& operator=(const B& b) = default;
    B(B&& b) = default;
    B& operator=(B&& b) = default;
};

class A {
public:
    A(B x) : x_(x) {}
    A(const A& a) = delete;
    A& operator=(const A& a) = delete;
    //move operations should be generated by compiler?
private:
    B x_;
};

int main() {
    A a = A(B());
}

我希望这可以编译并使用它的移动构造函数创建一个A,但是这会失败并显示以下消息:

error: use of deleted function ‘A::A(const A&)’
A a = A(B());
note: declared here
A(const A& a) = delete;

当然,添加移动操作并使用默认关键字标记它们可以解决问题.我应该假设移动操作不是由编译器生成的,为什么会这样? delete关键字是否将方法标记为用户实现,因此不会生成移动操作?为什么复制构造函数更喜欢?我正在使用gcc进行编译.

解决方法:

如果提供copy constructor / operator =的实现,则默认情况下不再生成移动操作.如果你想要它们,你需要明确告诉你这样做.

根据cppreference:

If no user-defined move constructors are provided for a class type
(struct, class, or union), and all of the following is true:

  • there are no user-declared copy constructors;
  • there are no user-declared copy assignment operators;
  • there are no user-declared move assignment operators;
  • there are no user-declared destructors;

then the compiler will declare a move constructor as a non-explicit
inline public member of its class with the signature T::T(T&&).

对于这种情况,这是一个有用的图表:

enter image description here
attribution

标签:move-constructor,c,c11,move-semantics,copy-constructor
来源: https://codeday.me/bug/20190823/1702601.html