cooky451
cooky451

Reputation: 3510

Implicitly generate move constructor

Is there any way a move constructor for a move-only class can be implicitly generated? Consider a class like this:

class moveable_only
{
  unique_ptr<int> p_;
};

moveable_only m;
foo(std::move(m));

This doesn't compile, because the implicitly declared copy constructor cannot copy p_. (12.8/7)

If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4).

Now consider this:

class moveable_only
{
  unique_ptr<int> p_;
  
   moveable_only(const moveable_only&);
   moveable_only& operator = (const moveable_only&);
};

moveable_only m;
foo(std::move(m));

This doesn't compile as well, because of 12.8/9

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,

— X does not have a user-declared destructor, and

— the move constructor would not be implicitly defined as deleted.

Upvotes: 1

Views: 1205

Answers (1)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234424

This doesn't compile, because the implicitly declared copy constructor cannot copy p_. (12.8/7)

There is no need for a copy constructor. This does not compile because your compiler does not seem to generate a move constructor automatically, which it should.

There is no way around that other than implementing it yourself or updating the compiler.

Upvotes: 4

Related Questions