通过在基类中声明复制构造函数/运算符private,可以使派生类不可复制? [英] Can a derived class be made uncopyable by declaring copy constructor/operator private in base class?

查看:350
本文介绍了通过在基类中声明复制构造函数/运算符private,可以使派生类不可复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这个问题的答案是肯定的。

I thought in theory the answer to this question was yes.

然而,在实践中,我的编译器(VS2010)似乎没有抱怨在以下情况:我有一个抽象基类提供一些通用接口(但没有数据成员),以及派生自它的各种子和子类。

However, in practice, my compiler (VS2010) does not seem to complain in the following situation: I have an abstract base class providing some common interface (yet having no data members) and various sub and subsubclasses derived from it.

class Base 
{
public:
    Base() {}
    virtual ~Base() {}

    virtual void interfaceFunction1() = 0;
    virtual void interfaceFunction2() = 0;
private:
    Base(const Base&);            // all derived classes should be uncopyable
    Base& operator=(const Base&);

    // no data members
};

我的编译器发现没有问题甚至在子类或子类中实现完全复制构造函数。

My compiler found it unproblematic to even implement full copy constructors in sub- or subsubclasses.

如何确保从Base派生的每个类都不可复制?

How can I make sure that every class derived from Base is uncopyable?

编辑:我理解的是,这正是Scott Meyers在Effective C ++(第三版,2005)的第6项中解释的,他对类 Uncopyable 的想法(只扩展到一个完整的接口类)。使他的想法工作有什么区别? (我知道他是私下继承的,但这不应该有问题)

edit: If I understand well, this is exactly what Scott Meyers explained in item 6 of Effective C++ (3rd edition, 2005) with his idea of the class Uncopyable (only extended here to a full interface class). What is the difference that makes his idea work ? (I know that he inherits privately, but this should not pose a problem)

推荐答案

这应该防止编译器生成副本没有明确声明一个派生类的构造函数。但是,没有什么可以阻止派生类显式声明一个复制构造函数,它将调用 Base 的复制构造函数。

This should prevent the compiler from generating a copy constructor for derived classes which do not declare one explicitly. However, nothing prevents a derived class from explicitly declaring a copy constructor which will do something else than call the copy constructor of Base.

没有办法确保派生类是可实例化的,但不可复制。

There is no way to make sure derived classes are instantiable but not copyable.

这篇关于通过在基类中声明复制构造函数/运算符private,可以使派生类不可复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆