【发布时间】:2016-02-01 10:51:31
【问题描述】:
在执行下面的代码时,它会打印两次“none”,但每次都打印不同的地址,即使它被声明为静态变量。
class singletonDemo {
private:
string text;
static singletonDemo s;
singletonDemo(string t2){ text = t2; }
public:
static singletonDemo getObject() {
return s;
}
void print() {
cout << text << endl;
}
};
singletonDemo singletonDemo::s("none");
int main() {
singletonDemo::getObject().print();
singletonDemo::getObject().print();
cout << "one: "<< &(singletonDemo::getObject()) << endl;
//cout << "print: " << single
cout << "two: " << &(singletonDemo::getObject()) << endl;
cout << "three: " << &(singletonDemo::getObject()) << endl;
system("pause");
}
我正在 Visual Studio Community 2013 中执行此代码。 请帮忙!
【问题讨论】:
-
你返回了一个对象的副本,但你实际上想要返回一个引用(
singletonDemo&或const singletonDemo&)。 -
没有明确的解决办法。尝试使用更经典的变体:C++ Singleton design pattern
-
对不起,我忘了删除“字符串”,现在它可以编译了。
标签: c++ oop memory static singleton