c++ - 是否可以通过删除基类中的复制构造函数/运算符来使派生类不可复制?

标签 c++ c++11 copy-constructor

Pre C++11,我问这是否可以使用私有(private)/未实现的技巧(参见 here)。显然,这是不可能的。

我想知道新的 = 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; 
};

最佳答案

不,派生类可以随意在其复制构造函数/赋值运算符中构造Base

class Derived : public Base {
public:
    Derived(){}
    Derived(const Derived&) : Base() {}
    void interfaceFunction() override {}
};

关于c++ - 是否可以通过删除基类中的复制构造函数/运算符来使派生类不可复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37595775/

相关文章:

c++ - 函数参数列表周围的双括号

c++ - 为什么多线程的 for 循环没有单线程的性能好?

c++ - 在C++中,如何正确获取指向 vector 的共享指针,最大限度地减少复制构造函数的调用次数?

C++ 双释放或损坏(出): Even with copy constructor and assignment operator

c++ - std::thread、类构造函数和析构函数

c++ - 在链表中移动和复制构造函数

c++ - 警告 : returning reference to temporary - strange case (Clarification for Rvalue)

c# - Windows 10 中的 SCHhangeNotify 不更新快速访问项目

c++ - 创建没有默认构造函数的对象数组

c++ - FindWindow( ... ) 不是 'finding' 创建的消息窗口