[英]why in singleton pattern , we do make copy constructor and assignment operator as private?
In a singleton pattern, typically we make the constructor/destructor private. 在单例模式中,通常我们将构造函数/析构函数设为私有。 That I understand because we don't want the user to create/delete the singleton object. 据我了解,因为我们不希望用户创建/删除单例对象。 There should be only way to get or create the instance. 应该只有获取或创建实例的方法。 However, I don't understand why do we need to make the copy constructor and assignment operator as private. 但是,我不明白为什么我们需要将复制构造函数和赋值运算符设置为私有。 What is the advantage of making the copy constructor and assignment operator private in singleton. 将复制构造函数和赋值运算符设置为单例私有的优点是什么。
Singleton obj1 = Singleton::CreateInstacnce();
Singleton obj2 = obj1; // copy ctr gets called
Singleton obj3;
obj3 = obj1; // assignment operator gets called
Therefore, if you don't make them private, multiple instance of Singleton class will be created 因此,如果您不将其设为私有,则将创建Singleton类的多个实例。
If you copy a singleton, you will have two objects of the same type. 如果复制单例,则将有两个相同类型的对象。 The purpose of singleton is to enforce only one instance. 单例的目的是仅强制执行一个实例。 Copying would break that assumption. 复制将打破该假设。
In a singleton pattern, we just want to instantiate only one object. 在单例模式中,我们只想实例化一个对象。 As you said, we we don't want the user to create/delete the singleton object, and we also don't want the user to copy the second object. 如您所说,我们不希望用户创建/删除单例对象,也不希望用户复制第二个对象。
Singleton obj1 = Singleton::CreateInstacnce();
Singleton obj2 = obj1; // copy ctr gets called
Singleton obj3;
obj3 = obj1; // assignment operator gets called
Here as per my opinion I feel only copy ctr should be private along with constructor. 根据我的观点,我觉得只有复制ctr应该与构造函数一起是私有的。
No need to make Assignment operator as private since Singleton obj3; 自Singleton obj3起,无需将Assignment运算符设置为私有; will anyways give the error saying that Singleton () is private. 无论如何都会给出错误,指出Singleton()是私有的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.