【发布时间】:2018-10-22 11:45:29
【问题描述】:
我在 singleton 类 下创建,并将复制构造函数和赋值运算符定义为私有。当我调用复制构造函数或赋值运算符时,它不会调用复制构造函数和赋值运算符(可能是由于静态对象创建)。所以我的问题是为什么单例设计模式允许创建对象的副本或分配新对象(这违反了创建类的单个实例化的基本要求)形式以前创建的对象,即使它们在类中被声明为私有?
请参考以下代码了解详情:-
#include <iostream>
#include "conio.h"
class singleton
{
static singleton *s;
int i;
singleton()
{
};
singleton(int x):i(x)
{ cout<<"\n Calling one argument constructor";
};
singleton(const singleton&)
{
cout<<"\n Private copy constructor";
}
singleton &operator=(singleton&)
{
cout<<"\n Private Assignment Operator";
}
public:
static singleton *getInstance()
{
if(!s)
{
cout<<"\n New Object Created\n ";
s=new singleton();
return s;
}
else
{
cout<<"\n Using Old Object \n ";
return s;
}
}
int getValue()
{
cout<<"i = "<<i<<"\n";
return i;
}
int setValue(int n)
{
i=n;
}
};
singleton* singleton::s=0;
int main()
{
// Creating first object
singleton *s1= singleton::getInstance();
s1->getValue();
singleton *s4=s1; // Calling copy constructor-not invoking copy ctor
singleton *s5;
s5=s1; // calling assignment operator-not invoking assign ope
//Creating second object
singleton *s2=singleton::getInstance();
s2->setValue(32);
s2->getValue();
//Creating third object
singleton *s3=singleton::getInstance();
s3->setValue(42);
s3->getValue();
getch();
return 0;
}
是我遗漏了什么还是我的理解有误。
请帮忙。 提前致谢。
【问题讨论】:
-
你复制的是指针,而不是对象。
-
如果构造函数是私有的,它甚至不允许单个对象
-
不是这样,类本身(及其朋友)被允许访问私有方法和成员,这正是您在
getInstance中所做的。 -
所以它将允许指针复制,以便我可以创建多个指向同一对象的指针。我的理解正确吗?
-
感谢您的接受。并欢迎投票水平 ;-)
标签: c++11 singleton copy-constructor assignment-operator