With explicitly deleted member functions in C++11, is it still worthwhile to inherit from a noncopyable base class?

Well, this:

private:
    MyClass(const MyClass&) {}
    MyClass& operator=(const MyClass&) {}

Still technically allows MyClass to be copied by members and friends. Sure, those types and functions are theoretically under your control, but the class is still copyable. At least with boost::noncopyable and = delete, nobody can copy the class.


I don’t get why some people claim it’s easier to make a class non-copyable in C++11.

It’s not so much “easier” as “more easily digestible”.

Consider this:

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

If you are a C++ programmer who has read an introductory text on C++, but has little exposure to idiomatic C++ (ie: a lot of C++ programmers), this is… confusing. It declares copy constructors and copy assignment operators, but they’re empty. So why declare them at all? Yes, they’re private, but that only raises more questions: why make them private?

To understand why this prevents copying, you have to realize that by declaring them private, you make it so that non-members/friends cannot copy it. This is not immediately obvious to the novice. Nor is the error message that they will get when they try to copy it.

Now, compare it to the C++11 version:

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

What does it take to understand that this class cannot be copied? Nothing more than understanding what the = delete syntax means. Any book explaining the syntax rules of C++11 will tell you exactly what that does. The effect of this code is obvious to the inexperienced C++ user.

What’s great about this idiom is that it becomes an idiom because it is the clearest, most obvious way to say exactly what you mean.

Even boost::noncopyable requires a bit more thought. Yes, it’s called “noncopyable”, so it is self-documenting. But if you’ve never seen it before, it raises questions. Why are you deriving from something that can’t be copied? Why do my error messages talk about boost::noncopyable‘s copy constructor? Etc. Again, understanding the idiom requires more mental effort.

Leave a Comment