CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Clean up declaration and implementation of clone functions

Open hsutter opened this issue 5 years ago • 2 comments

Clarify C.67 and C.130 to say that suppressing copy construction should mean not having a public one, and that the Clone pattern could be done in terms of a private copy constructor.

hsutter avatar Jun 04 '20 18:06 hsutter

There are a few issues in the C.21 example:

  1. A typo in the constructor: CloneableBase -> ClonableBase (or maybe the class should be called CloneableBase).

  2. The deleted copy operator in the base class doesn't allow to implement the clone method in a derived class. The below code doesn't compile:

     class ClonableDerived : public ClonableBase {
        public:
         std::unique_ptr<ClonableBase> clone() const {
             return std::make_unique<ClonableDerived>(*this);
         }
     };
    
  3. The order contradicts with NL.16.

Taking into account the above issues I'd prose the below example:

    class ClonableBase {
    public:
        ClonableBase() = default;
        virtual ~ClonableBase() = default;
        virtual std::unique_ptr<ClonableBase> clone() const;
        // ... other constructors and functions ...

    protected:
        ClonableBase(const ClonableBase&) = default;
        ClonableBase& operator=(const ClonableBase&) = default;
        ClonableBase(ClonableBase&&) = default;
        ClonableBase& operator=(ClonableBase&&) = default;

    };

oleksandrkozlov avatar Nov 14 '21 15:11 oleksandrkozlov

Since cloning is covered in C.130, can the cloning example be removed from C.21. Maybe replace it with an example that has copy deleted and move defined to show that they don't all have to be the same?

bgloyer avatar Nov 15 '21 06:11 bgloyer