Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function returning a static instance of the class - shouldn't the instance be the same?

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?

like image 466
user2018675 Avatar asked May 26 '26 13:05

user2018675


2 Answers

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();
like image 75
Jarod42 Avatar answered May 28 '26 02:05

Jarod42


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.

like image 33
songyuanyao Avatar answered May 28 '26 03:05

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!