c_cpp C.67:基类应该禁止复制,如果需要“复制”,则提供虚拟克隆。原因:为了防止切片,因为

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C.67:基类应该禁止复制,如果需要“复制”,则提供虚拟克隆。原因:为了防止切片,因为相关的知识,希望对你有一定的参考价值。

/*
C.67: A base class should suppress copying, and provide a virtual clone instead if "copying" is desired

Reason

To prevent slicing, because the normal copy operations will copy only the base portion of a derived object.
*/

// Example, bad

class B { // BAD: base class doesn't suppress copying
    int data;
    // ... nothing about copy operations, so uses default ...
};

class D : public B {
    string moredata; // add a data member
    // ...
};

auto d = make_unique<D>();
auto b = make_unique<B>(d); // oops, slices the object; gets only d.data but drops d.moredata

// Example, Good

class B { // GOOD: base class suppresses copying
    int data;

    B(const B&) =delete;
    B& operator=(const B&) =delete;
    virtual unique_ptr<B> clone() { return /* B object */; }
    // ...
};

class D : public B {
    string moredata; // add a data member
    unique_ptr<B> clone() override { return /* D object */; }
    // ...
};

auto d = make_unique<D>();
auto b = d.clone(); // ok, deep clone


// TODO: COVARIANT return type does not exist for smart pointers. So try to complete the above snippet.

以上是关于c_cpp C.67:基类应该禁止复制,如果需要“复制”,则提供虚拟克隆。原因:为了防止切片,因为的主要内容,如果未能解决你的问题,请参考以下文章