C++ Logo

std-discussion

Advanced search

Example showing superfluous code

From: Peter Sommerlad (C++) <"Peter>
Date: Tue, 6 Jul 2021 10:44:31 +0200
In [dcl.fct.def.delete] the following example demonstrates the use of
=delete but does so superfluously, because default declaration of the
move operations implicitly suppress the copy operations.


[Example 3: One can make a class uncopyable, i.e., move-only, by using
deleted definitions of the copy constructor and copy assignment
operator, and then providing defaulted definitions of the move
constructor and move assignment operator.
struct moveonly {
  moveonly() = default;
  moveonly(const moveonly&) = delete;
  moveonly(moveonly&&) = default;
  moveonly& operator=(const moveonly&) = delete;
  moveonly& operator= (moveonly&&) = default;
  ~moveonly() = default;
};
moveonly* p;
moveonly q(*p); // error: deleted copy constructor
—end example]


I would like to suggest to change that example to show a situation where
using =delete really is useful and requires less code:

[Example 3: One can make a polymorphic base class non-copyable and
non-movable to prevent slicing by defining the move-assignment operator
as deleted.

struct polybase {
  virtual ~polybase() = default;
  polybase& operator=(polybase&&) & = delete;
};

polybase* pb;
polybase q(*pb); // error: copy constructor implicitly deleted
polybase r;
r = std::move(*pb); // error: move assignment deleted
--end example]


What do people think?

Regards
Peter.


-- 
Peter Sommerlad
Better Software: Consulting, Training, Reviews
Modern, Safe & Agile C++
peter.cpp_at_[hidden]
+41 79 432 23 32

Received on 2021-07-06 03:44:39