简体   繁体   English

在设计Singleton模式时是否需要使赋值运算符私有

[英]Is it neccessary to make assignment operator private while designing Singleton pattern

I have just Learned about the first Design Pattern in my career :) and Implemented it both using early and Lazy method. 我刚刚了解了我职业生涯中的第一个设计模式:),并使用早期和惰性方法实现了它。 While it is Logical to make the Copy Constructor Private but i was told that also make assignment operator private. 虽然将Copy构造函数设为私有是合乎逻辑的,但有人告诉我也将赋值运算符设为私有。 Since only one instance can be created I think it does not make sense to declare Assignment operator private. 由于只能创建一个实例,因此我认为将Assignment运算符声明为private没有意义。

Since only one instance can be created I think it does not make sense to declare Assignment operator private. 由于只能创建一个实例,因此我认为将Assignment运算符声明为private没有意义。

It does not make sense to declare Assignment operator at all. 完全没有必要声明Assignment运算符。 Anyway you're right. 反正你是对的。 public or private it does make any difference because it will never be used. publicprivate ,确实有任何区别,因为它将永远不会被使用。

For those reasons the most practical choice is to avoid to define it at all, and make sure it cannot be called: C++11 has introduced that functionality. 由于这些原因,最实际的选择是完全避免定义它,并确保它不能被调用: C ++ 11引入了功能。

So, you can just delete it. 因此,您可以删除它。

Singleton& operator=(const Singleton&) = delete;

They may have been referring to an assignment operator which performs copying: 他们可能已经引用执行复制的赋值运算符:

Singleton& operator=(const Singleton& other);

This implies multiple instances of Singleton, since you would need another instance (the 'other') to copy into the Singleton instance, which doesn't make sense. 这意味着存在多个Singleton实例,因为您需要将另一个实例(“其他”)复制到Singleton实例中,这没有任何意义。 Therefore, you can make it private or mark it as deleted. 因此,您可以将其设为私有或将其标记为已删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在单例模式中,我们将复制构造函数和赋值运算符设为私有? - why in singleton pattern , we do make copy constructor and assignment operator as private? 在单例设计模式中使用复制构造函数和赋值运算符 - Use of copy constructor and assignment operator in singleton design pattern 在Singleton设计模式下,我们如何使析构函数私有? - How can we make the destructor private in case of Singleton design pattern? 什么时候我们应该将赋值运算符设为私有而不实现 - when should we make assignment operator private and don’t implement 当我制作 class 模板时,赋值运算符崩溃代码 - Assignment operator crashes code while i make template of class 禁止复制构造函数和赋值运算符singleton类 - prohibit copy constructor and assignment operator singleton class Singleton class 中需要私有化赋值运算符 - Need of privatizing assignment operator in a Singleton class 为什么我要将复制构造函数和赋值运算符设为私有并在C ++中实现? - Why would I make copy constructor and assignment operator private and implemented in C++? 从私有向量公开访问和分配运算符 - Expose access and assignment operator from private vector 在Copy Constructor和Assignment运算符中删除私有数组 - Deleting Private Array in Copy Constructor and Assignment operator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM