静态函数返回类的静态实例 - 实例应该不一样吗?

use*_*675 2 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;
}
Run Code Online (Sandbox Code Playgroud)

我认为a并且b应该有相同的地址,因为我认为它们应该只构造一次.但是,我在此测试中获得了不同的memmory地址.

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

Jar*_*d42 7

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

你可能想要

Test& a = Test::get();
Test& b = Test::get();
Run Code Online (Sandbox Code Playgroud)