简体   繁体   English

为什么要在C ++中为单例类重载复制赋值运算符?

[英]Why overload copy assignment operator for a singleton class in C++?

I know why to make default constructor and copy constructor private to implement singleton class in C++. 我知道为什么要使默认构造函数和复制构造函数私有以在C ++中实现单例类。 But what I don't understand is that why make copy assignment operator private, because there will not be two existing objects to start with. 但是我不明白的是为什么将拷贝分配运算符设为私有,因为不会有两个现有的对象开始。

My exploration brings two points: 我的探索有两点:

  1. According to Alexandrescu in "Modern C++ Design", the assignment operator to be made private to prevent self-assignment. 根据Alexandrescu在“ Modern C ++ Design”中的说法,将赋值运算符设为私有,以防止自我赋值。

  2. Second, according to rule of three , if you define one of ctor, copy ctor and assignment operator for a class, you should define explicitly all three. 其次,根据三个规则 ,如果您为类定义ctor,copy ctor和赋值运算符之一,则应显式定义所有三个。 So, is it a matter of following this rule only. 因此,仅遵循此规则是一个问题。

So, what's your take on this? 那么,您对此有何看法?

I think, the need to prohibit the assignment is more in semantic considerations: as singleton is unique , the assignment for it doesn't have any sense. 我认为,禁止分配的需求更多是出于语义方面的考虑:由于singleton是唯一的 ,因此对其分配没有任何意义。 So if it would be even technically possible to implement assignment in a reasonable way, logically you need to prohibit it anyway. 因此,即使从技术上讲,以合理的方式实现分配也是可行的,但从逻辑上讲,您还是必须禁止分配。

So exactly because there must be never a need to copy a singleton, the operation has to be prohibited. 正是因为绝对不需要复制单例,所以必须禁止该操作。 Otherwise there is a room for confusion and mistakes: the developers will try to use it if it's allowed (and wonder what's wrong). 否则,会有混乱和错误的余地:如果允许的话,开发人员尝试使用它(并想知道哪里出了问题)。

The good design minimizes the amount of WTFs. 好的设计可以最大程度地减少WTF的数量。

No. 没有。

In a Singleton you want to manage all possible construction, assignment and destruction. 在Singleton中,您要管理所有可能的构造,分配和销毁。 By making all those operations private you actually just prevent others from using them. 通过将所有这些操作private您实际上只是在阻止其他人使用它们。

Also note that typically copy construction and copy assignment will be declared private to prevent invocation from outside but will not be defined because they are not used in practice... and so if they were the linker would complain. 还要注意,通常将复制构造和复制分配声明为private以防止从外部调用,但由于在实践中未使用它们而未定义它们,因此如果链接器会抱怨。

In C++11 you would declare copy construction and copy assignment as delete d. 在C ++ 11中,您将复制构造和复制分配声明为delete d。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM