Вопрос

I am a little confused about how best to define a copyable but not moveable class. It seems to me that deleting the move constructor is a bad idea because then I couldn't construct from a temporary. On the other hand I don't want the compiler to implicitly generate a move constructor for me that may be wrong or may lead to unexpected behavior. My question is whether the compiler is allowed to implicitly generate a move constructor for the following class:

class C {
    public:
    int i_;
    C(const C&) = default;
}
Это было полезно?

Решение 2

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if

  • X does not have a user-declared copy constructor
  • [and ...]

Since the copy constructor is user-declared (even though it is defaulted, which means it is not user-provided), a move constructor will not be implicitly declared as defaulted.

You're right that if you were to explicitly delete the move constructor, you would not be able to construct from temporaries because the deleted move constructor would be chosen by overload resolution. So the approach you have used for a copyable but not moveable class is the right one.

Другие советы

[class.copy]/9 after CWG 1402:

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if

  • X does not have a user-declared copy constructor,
  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator, and
  • X does not have a user-declared destructor.

Relative to your example the compiler will implicitly declare a move constructor because the first declaration of your copy constructor is the default definition. In this case the copy constructor is considered as implicitly defined. But if you would change your class definition the following way

class C {
    public:
    int i_;
    C(const C&);
};

C::C( const C & ) = default;

then in this case the move constructor would not be generated by the compiler becasue the copy constructor is explicitly declared by the user.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top