简体   繁体   English

在单例设计模式中使用复制构造函数和赋值运算符

[英]Use of copy constructor and assignment operator in singleton design pattern

My doubt in Singleton design pattern is if it's enough to just make the constructor private. 我对Singleton设计模式的怀疑是,是否足以将构造函数设为私有。 I think there is no need to make the copy constructor and assignment operator private. 我认为没有必要将复制构造函数和赋值运算符设为私有。

Since we can not create the object, (object will be created by a static function and will be allocated in static pointer) then the copy constructor or assignment operator will not be invoked. 由于我们无法创建对象(对象将由静态函数创建,并将在静态指针中分配),因此将不会调用复制构造函数或赋值运算符。 Is this right? 这是正确的吗?

That's wrong. 错了 If you receive a pointer to an internally allocated instance, you could still make a copy of it if the copy constructor is public. 如果收到指向内部分配的实例的指针,则在复制构造函数为public的情况下,仍可以对其进行复制。 For example: 例如:

Singleton * s = Singleton::getInstance();

Singleton copy = *s;   // <-- invokes copy constructor

Similar problem with the assignment operator: 赋值运算符的类似问题:

Singleton * s1 = Singleton::getInstance();
Singleton * s2 = Singleton::getInstance();

*s1 = *s2;    // <-- invokes assignment operator (although self-assignment...)

Both of these won't do much harm, but they're violating the intent of the Singleton pattern. 这两个都不会造成太大的伤害,但是它们违反了Singleton模式的意图。

By making both copy constructor and assignment operator private, you solve the problem. 通过将复制构造函数和赋值运算符都设为私有,可以解决此问题。 Since C++11, you can also "delete" them, by writing 从C ++ 11开始,您还可以通过编写“删除”它们

Singleton(const Singleton&) = delete;               // copy constructor
Singleton & operator=(const Singleton&) = delete;   // assignment operator

No need to make the copy constructor (and assignment operator) private, as by default they would use shallow copy. 无需将复制构造函数(和赋值运算符)设为私有,因为默认情况下,它们将使用浅表复制。 However, why would you want to implement a copy constructor in a Singleton class? 但是,为什么要在Singleton类中实现复制构造函数? If you implement a copy constructor, and implement deep copying in it, and keep it public, well, then multiple objects of the class can be created. 如果实现一个复制构造函数,并在其中实现深层复制,并使其保持公开状态,那么可以创建该类的多个对象。

If you are using C++11, best would be to delete them: 如果使用的是C ++ 11,最好将其删除:

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

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

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