0

In the book "C++ Programming language" by Bjarne Stroustrup when talking about exceptions it says the following:

An exception is object thrown to represent the occurrance of an error. It can be of any type that can be copied but it is strongly recommended to use only user-defined types specifically defined for that purpose.

Reasoning about it I cannot immediately think of objects that cannot be copied. What are types that cannot be copied in C++?

roschach
  • 8,390
  • 14
  • 74
  • 124

1 Answers1

5

To be copyable an object must define at least one of two possible ways of being copied:

  • copy assignment T& operator=(const T&)
  • copy constructor T(const T&)

If no one of these is defined or it has been explicitly deleted (= delete) then you can't copy the object.

The requirement arises from the fact that exception handling must be able to copy the exception object itself somewhere for proper management.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • So I can use `delete` to delete the default copy constructor? Syntax is like this: `T(const T&) = delete;`? Do I have also to delete the copy assignment? – roschach Feb 16 '19 at 13:45
  • 1
    deleted or declared private (the only method in C++98) – Clifford Feb 16 '19 at 13:46
  • These must be done for both copy assignment and copy constructor or just one? What about C++11 move operators? – roschach Feb 16 '19 at 13:51
  • @Clifford: yes, actually making it private doesn't make it uncopyable. It makes the object uncopyable from outside code, but you're still allowed to copy it, eg: https://ideone.com/HpazXw – Jack Feb 16 '19 at 13:54
  • 1
    @FrancescoBoi: refer to this for general behavior https://stackoverflow.com/questions/33096653/make-a-class-non-copyable-and-non-movable, you need to delete both operators to make it uncopyable and being movable is a different concept. – Jack Feb 16 '19 at 13:55
  • @Jack : Yes - good point; it is not semantically identical. However it renders it uncopyable for the purposes of exception handling since it is not copyable by any means the exception handling will be aware of. I think the Stroustrup text predates C++98 let alone C++11 when deleting member functions was not a thing in C++, so private membership would have been the method at the time. Often code lasts longer than C++ standards, so I make the point only because the technique may bee seen in maintenance or written by dinosaurs like me who often see little reason to change. – Clifford Feb 16 '19 at 14:18
  • I kind of take that back - the text in the pre-C++11 third edition does not mention the copyability of an exception object. So the author will have had member deletion in mind perhaps. – Clifford Feb 16 '19 at 14:27