2

If I want to forbid copy construction/assignment then is:

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

The same as:

class foo
{
private:
   foo(const foo&) = default;
   foo& operator = (const foo&) = default;
};

Which is the right way and why?

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
paulm
  • 5,629
  • 7
  • 47
  • 70

1 Answers1

4

The right way is the first solution : the copy constructor and assignment operators are not defined, so any attempt to use them will not compile.

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

The second is declaring and defining the implicitly generated forms as private :

  • An object of type foo is allowed to copy itself.
  • Any friend class or method is also allowed to copy a foo

So copy construction/assignment is still possible.

You could also use boost::noncopyable as a base class, it does exactly that with c++11 (see the source code here)

quantdev
  • 23,517
  • 5
  • 55
  • 88
  • Yeah, even with the delete thingy to disable certain member functions added in C++11 I still prefer boost::noncopyable as it makes the intent obvious with a simple glance and also takes much less typing. – antred Oct 13 '14 at 13:04