Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncopyable class with automatic default and move constructors

I want to make some classes use automatically generated constructors, but be non-copyable (but still movable). Currently I'm doing it like this:

class A
{
public:
    A() = default;
    A(const A&) = delete;
    A(A&&) = default;
    A& operator=(const A&) = delete;
    A& operator=(A&&) = default;
}

I wonder if it's really necessary to be so explicit. What if I wrote it like this:

class A
{
    A(const A&) = delete;
    A& operator=(const A&) = delete;
}

Would it still work the same? What is the minimal set of defaults and deletes for other cases - non-copyable non-movable class, and class with virtual destructor?

Is there any test code I can use to quickly see which constructors are implicitly created?

like image 277
Xirdus Avatar asked May 18 '14 13:05

Xirdus


1 Answers

This will not work because no default constructor will be automatically created for you. No default constructor will be created because you have declared a copy constructor. It is defined as deleted, but it is user-declared nonetheless, so there is no implicitly defaulted default constructor.

The condensed rules for implicitly created constructors are:

  • The defaulted move constructor and the defaulted move assignment operator are created implicitly unless you have declared any other of the Big 5 special functions (and unless prevented by non-movable members or bases)
  • The defaulted default constructor (what a name!) is created implicitly unless you have declared any constructor (and unless prevented by non-default-creatable members or bases)
  • The defaulted copy constructor and the defaulted copy assignment operator are created unless you have declared the move constructor or the move assignment operator (and unless prevented by non-copyable members or bases)
like image 132
4 revs Avatar answered Sep 19 '22 01:09

4 revs