静态函数返回类的静态实例 - 该实例是否应该相同?

时间:2015-03-27 01:46:24

标签: c++ static-methods

我有以下代码:

#include <iostream>
using namespace std;

class Test {
public:
  static Test& get() {
    static Test testSing;
    return testSing;
  }
};

int main() {
  Test a = Test::get();
  Test b = Test::get();

  cout << &a << endl;
  cout << &b << endl;
}

我认为ab应该具有相同的地址,因为我认为they should be constructed only once。但是,我在此测试中获得了不同的memmory地址。

我缺少一些微不足道的东西吗?他们不应该有相同的地址吗?

3 个答案:

答案 0 :(得分:7)

您使用复制构造函数,因此您有2个不同的对象,缺少引用。

你可能想要

Test& a = Test::get();
Test& b = Test::get();

答案 1 :(得分:4)

ab是从Test::get的返回值分配的,这意味着它们被复制,因此它们是独立变量。您可以将它们声明为引用类型,因此请将代码更改为:

Test &a = Test::get();
Test &b = Test::get();

你会得到你想要的东西。

答案 2 :(得分:4)

  

&#34;我认为a和b应该具有相同的地址&#34;

正如其他答案所述,您指的是Test的副本,当然它们的地址也不同。

要使它成为单例类(似乎是预期的),您明确禁止使用默认和复制构造函数,以及复制赋值运算符:

class Test {
public:
  static Test& get() {
    static Test testSing;
    return testSing;
  }
private:
    // Forbid the following operations being used from public scope
    Test() {}
    Test(const Test&);
    Test& operator=(const Test&);
};

这样,除了意外行为之外,您首先会得到简明的编译错误。

相关问题