【问题标题】:function returning different address of static object函数返回静态对象的不同地址
【发布时间】: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&amp;const singletonDemo&amp;)。
  • 没有明确的解决办法。尝试使用更经典的变体:C++ Singleton design pattern
  • 对不起,我忘了删除“字符串”,现在它可以编译了。

标签: c++ oop memory static singleton


【解决方案1】:

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

您不打印静态变量的地址。您打印由getObject 返回的静态变量的两个单独副本的地址。该程序格式错误,因为不允许您将 address-of 运算符与临时对象一起使用。

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

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

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2012-09-08
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多