通过删除基类中的复制构造函数/运算符,可以使派生类不可复制吗?

mr_*_*r_T 4 c++ copy-constructor c++11

在C ++ 11之前,我问是否可以使用私有/未实现的技巧(请参阅此处)。显然,这是不可能的。

我不知道新= delete语法是否改变了事务状态,因为强制派生类不可复制仍然是有用的功能。

经过更新的代码段可能类似于以下内容:

class Base 
{
public:
    Base() {}
    virtual ~Base() {}
    Base(const Base&) = delete;
    Base& operator=(const Base&) = delete;

    virtual void interfaceFunction() = 0;
    // etc.

    // no data members
};

class Data { /* ... */ };
class Derived : public Base  // is this class uncopyable ?
{
    Derived() : managedData(new Data()) { }
    ~Derived() ( delete managedData; }

    virtual void interfaceFunction() override { /* ... */ }

    Data* managedData; 
};
Run Code Online (Sandbox Code Playgroud)

Chr*_*rew 5

不,派生类可以根据需要随意Base在其复制构造函数/赋值运算符中进行构造。

class Derived : public Base {
public:
    Derived(){}
    Derived(const Derived&) : Base() {}
    void interfaceFunction() override {}
};
Run Code Online (Sandbox Code Playgroud)

  • 轻松解决:删除Base的* all *构造函数。现在,任何“派生”类型都无法复制“基本”!(完全不能保证可以创建`Derived`类) (2认同)