59

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

I'm talking about the trick where you privately inherit a base class which has private or deleted copy constructor and copy assignment (e.g. boost::noncopyable).

Are the advantages put forward in this question still applicable to C++11?


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

In C++03:

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

In C++11:

MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;

EDIT:

As many people have pointed out, it was a mistake to provide empty bodies (i.e. {}) for the private copy constructor and copy assignment operator, because that would allow the class itself invoke those operators without any errors. I first started out not adding the {}, but ran into some linker issues that made me add the {} for some silly reason (I don't remeber the circumstances). I know better know. :-)

Community
  • 1
  • 1
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
  • 2
    You're not describing an idiom, but merely one implementation of it. The idiom remains, and it is now simpler to write. – Kerrek SB Feb 27 '12 at 00:42
  • How is it simpler than writing an empty private copy constructor and private copy assignment operator? – Emile Cormier Feb 27 '12 at 00:45
  • Edited to avoid misuse of the term 'idiom'. – Emile Cormier Feb 27 '12 at 00:47
  • 2
    http://stackoverflow.com/a/7841332/576911 – Howard Hinnant Feb 27 '12 at 00:49
  • 9
    @Emile: you don't want the `{}` in your C++03 example (that allows copies within member functions). – Michael Burr Feb 27 '12 at 00:54
  • 15
    "I don't get why some people claim it's easier to make a class non-copyable in C++11." Your own example shows one reason it is easier: you got the C++03 example wrong. – R. Martinho Fernandes Feb 27 '12 at 00:57
  • @MichaelBurr : I'm usually worried about users of the class making copies, but your point is valid nonetheless. – Emile Cormier Feb 27 '12 at 00:59
  • @Emile: there may be times when you want to be able to copy only within the class, but in my experience, most of the time when you want non-copy semantics, it's because it *never* makes sense to copy. That said, I think inheriting from a "noncopy" mix-in class is for the moment more readable than using `= delete` for me. I suspect that over time the `= delete` method will become as readily readable to me. – Michael Burr Feb 27 '12 at 01:47
  • @EmileCormier: If you claim something is an idiom, you're not really free to change it. R.Martinho Fernandes is *exactly right* - you've got it wrong, and you didn't even realize you did! You've shot yourself in the foot. Your C++03 example is definitely non-idiomatic. It is *always* an error for a class to be publicly non-copyable but privately copyable with *empty* bodies for the constructor/assignment operator. If there's a corner case that would benefit from such misbehavior, it's still an error, albeit an architectural one. – Kuba hasn't forgotten Monica Oct 07 '13 at 21:11
  • @KubaOber: Ouch! http://xkcd.com/386/ – Emile Cormier Oct 08 '13 at 13:13
  • @EmileCormier: Like, duh! :) Otherwise known as human nature :) The linker "issues" are precisely why the C++11 way is better. You thought it was a linker "issue", but the linker was **in fact preventing you from shooting yourself in the foot**! In C++03, this idiom makes the linker report errors in your code to you. In C++11, deleting the constructors makes the compiler report the error. As *you've yourself shown*, you don't believe the linker. So you've added the empty definitions. And you've got code that silently does the wrong thing. You've just answered it, for yourself. With some help:) – Kuba hasn't forgotten Monica Oct 08 '13 at 13:57
  • @EmileCormier: I think the answer should be: C++11 way is better because of human nature, that's why. Because humans these days don't know what the linker does so they don't think so if a linker "pops an error" they'll take the route of the least resistance to silence it. Making their code do wrong, incorrect things. I mean, man, I don't think there's any better argument for the C++11 way. – Kuba hasn't forgotten Monica Oct 08 '13 at 14:02

5 Answers5

78

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 12
    +1 I like how you illustrate that `= delete` is not necessarily easier to write, but easier to *read*. – Emile Cormier Feb 27 '12 at 01:11
  • 1
    I just want to note that private ctor and copy assignment operators without defined body would do the trick. One could just declare `MyClass(const MyClass&);` instead of providing empty defintion `MyClass(const MyClass&) {}` and this way class is non-copy-constructible within itself. However `= delete` makes programmer's intentions clear and is self-explanatory. – mip Sep 03 '15 at 14:16
24

The first thing is that as others before me point out, you got the idiom wrong, you declare as private and don't define:

class noncopyable {
   noncopyable( noncopyable const & );
   noncopyable& operator=( noncopyable const & );
};

Where the return type of the operator= can be basically anything. At this point, if you read that code in a header, what does it actually mean? It can only be copied by friends or it cannot be copied ever? Note that if you provide a definition as in your example, it is stating that I can be copied only inside the class and by friends, it is the lack of a definition what translates this into I cannot be copied. But the lack of a definition in the header is not a synonym for a lack of definition everywhere, as it could be defined in the cpp file.

This is where inheriting from a type called noncopyable makes it explicit that the intention is to avoid copies, in the same way that if you manually wrote the code above you should document with a comment in the line that the intention is disabling copies.

C++11 does not change any of this, it just makes the documentation explicit in the code. In the same line that you declare the copy constructor as deleted you are documented that you want it fully disabled.

As a last comment, the feature in C++11 is not just about being able to write noncopyable with less code or better, but rather about inhibiting the compiler from generating code that you don't want generated. This is just one use of that feature.

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • 3
    **You've raised a very important point**: the empty private implementations don't prevent yourself from erroneously copying the object! The idiom is *not* to provide empty private definitions. The idiom is to provide *declarations only*. – Kuba hasn't forgotten Monica Oct 07 '13 at 21:07
  • 1
    @Kuba this solution doesn't work with some standards-conforming compilers/linkers, as they require that when you declare a member function you must also define it. For example, the Green Hills compiler/linker will fail with a linker error regarding missing definitions for your copy ctor and assignment operator, even if no code uses them. – ThreeBit Jan 07 '14 at 23:00
  • 1
    That's interesting. I'd consider such a compiler/linker combo to be broken, since there is a whole darn lot of code that uses this idiom without providing definitions. The entire Qt toolkit comes to mind. – Kuba hasn't forgotten Monica Jan 07 '14 at 23:03
  • 1
    @ThreeBit: The standard does not require definitions for entities that are not *odr-used* (in C++11 parlance, *used* in C++98 parlance). A toolchain that requires the definitions would reject correct programs. – David Rodríguez - dribeas Jan 08 '14 at 04:08
10

In addition to the points others have brought up...

Having a private copy constructor and copy assignment operator that you do not define prevents anyone from making copies. However, if a member function or friend function attempts to make a copy, they will receive a link-time error. If they attempt to do so where you have explicitly deleted those functions, they will receive a compile-time error.

I always make my errors occur as soon as possible. Make run-time errors happen at the point of error instead of later on (so make the error happen when you change the variable instead of when you read it). Make all run-time errors into link-time errors so the code never has a chance to be wrong. Make all link-time errors into compile-time errors to speed up development and have slightly more useful error messages.

David Stone
  • 26,872
  • 14
  • 68
  • 84
5

It's more readable and allows the compiler to give better errors.

The 'deleted' is more clear to a reader, especially if they're skimming over the class. Likewise, the compiler can tell you that you're trying to copy a non-copyable type, instead of giving you a generic 'trying to access private member' error.

But really, it's just a convenience feature.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
2

People here are recommending that you declare member functions without defining them. I would like to point out that such an approach isn't portable. Some compilers/linkers require that if you declare a member function then you must also define it, even if it isn't used. If you are using only VC++, GCC, clang then you can get away with this, but if you are trying to write truly portable code then some other compilers (e.g. Green Hills) will fail.

ThreeBit
  • 608
  • 6
  • 17
  • 1
    I am skeptical of this answer. Because it's legal to define the member functions of a class across multiple compilation units it would actually be difficult to implement this anti-feature. Example that works with gcc/clang/icc? – Praxeolitic Jun 18 '14 at 07:28