人们为什么要定义私有复制构造函数?
什么时候将复制构造函数和赋值运算符设为私有是一个好的设计?
如果类中没有作为唯一对象(如文件名)的指针或句柄的成员,那么在其他情况下,私有复制构造函数是个好主意吗?
同样的问题也适用于赋值运算符。鉴于大多数 C++ 都围绕对象复制和引用传递,是否有涉及私有复制构造函数的良好设计?
一个用例是单例模式 where 一个类只能有一个实例。在这种情况下,您需要将构造函数和赋值运算符设置为私有,这样就无法创建多个对象。创建对象的唯一方法是通过 GetInstance() 函数,如下所示。
// An example of singleton pattern
class CMySingleton
{
public:
static CMySingleton& GetInstance()
{
static CMySingleton singleton;
return singleton;
}
// Other non-static member functions
private:
CMySingleton() {} // Private constructor
~CMySingleton() {}
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator=(const CMySingleton&); // Prevent assignment
};
int main(int argc, char* argv[])
{
// create a single instance of the class
CMySingleton &object = CMySingleton::GetInstance();
// compile fail due to private constructor
CMySingleton object1;
// compile fail due to private copy constructor
CMySingleton object2(object);
// compile fail due to private assignment operator
object1 = object;
// ..
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)