3

I have the following code:

#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;
}

I thought that a and b should have the same address, since I thought they should be constructed only once. However, I get different memmory addresses in this test.

Is there something trivial that I am missing? Shouldn't they have the same address?

Community
  • 1
  • 1
user2018675
  • 657
  • 2
  • 5
  • 15

3 Answers3

8

You use the copy constructor, so you have 2 different objects, references are missing.

You probably want

Test& a = Test::get();
Test& b = Test::get();
Jarod42
  • 203,559
  • 14
  • 181
  • 302
4

a and b are assigned from the return value of Test::get, that mean they are copied, so they are independent variables. You may declare them as reference type, so change the code to:

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

You'll get what you want.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
4

"I thought that a and b should have the same address"

As mentioned in the other answers, you're referring to copies of Test, and their addresses are different of course.

To make it a singleton class (as it seems to be intended) you explicitly prohibit using the default and copy constructors, and copy assignment operators:

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&);
};

This way you'll get concise compilation errors in first place, besides unexpected behavior.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190