在执行以下代码时,它两次打印“无”,但每次都打印不同的地址,即使声明为静态变量也是如此。

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中执行此代码。
请帮忙!

最佳答案

但是每次都打印不同的地址,即使它被声明为静态变量。


您不打印静态变量的地址。您打印两个静态副本的地址,这些副本由getObject返回。该程序格式不正确,因为不允许您对临时对象使用address-of运算符。

返回副本可能是一个错误,并且您可能打算返回对静态变量static singletonDemo& getObject()的引用。

为了防止此类错误,我建议您在单例设计中不要使用(n个隐式)公共副本或移动构造函数。

09-04 16:05
查看更多