0

我们可能同意默认复制构造在 C++ 中大部分时间都很糟糕,因此最好使用 C++11=delete或不可复制的类(如boost::noncopyable.

问题是,当我们使用多重继承或公共抽象类时,在高级场景中会发生什么?

//Class uncopyable
class uncopyable {...};

//Interface1
class IInterface1 : private uncopyable
{
public:
 IInterface1(...)
 virtual ~IInterface1(...) = 0;
};

//Interface2
class IInterface2 : private uncopyable
{
public:
 IInterface2(...)
 virtual ~IInterface2(...) = 0;
};

//Fancy implementation
//FImpl
class FImpl : public IInterface1, public IInterface2, private : uncopyable
{
public:
 FImpl(...) {...}
 ~FImpl(...) {...};
};
  • 使每个接口都不可复制(似乎是,以避免切片)是一种好习惯吗?
  • 向每个派生类添加不可复制是一种好习惯(显式保护,但会导致多重继承和菱形问题?)
4

2 回答 2

1

不,使界面不可复制不是一个好主意。例如,这可以防止克隆。

不,从每个派生类中的不可复制派生不是一个好主意,因为它只是多余的。

但是,为了特别阻止 Visual C++ 发出愚蠢的警告,最好在每个应该是不可复制的类中声明一个复制构造函数和复制赋值运算符。

于 2012-08-04T15:17:53.207 回答
0

A pure virtual (interface) class has no need to enforce the memory management for the use of the interface. Implementations of pure virtual interfaces should determine their own memory management requirements (like copy and assign).

That said, value semantics allow implementations to avoid this situation entirely. A value class (copyable, assignable, etc.) is easier to reason about and use. All of the classes in the C++ library are value classes. A good example of a value class managing memory for itself is the venerable string class. Vector is also a good example. These classes have complex internal memory management requirements, yet, as a user of these classes, I don't have to be concerned with that aspect of the class. I can focus on how to use the class.

I like this presentation from C++ Now that shows how polymorphism is also an implementation detail. This includes the ability for a client to implement classes that can participate in the polymorphism without requiring an interface class (or any base class for that matter).

于 2012-08-04T19:19:58.950 回答