0

I expected that, when we define a static member as singleton's instance, the getInstance() should always return the same object address, so I tried:

struct singleton {
    static auto& getInstance() {
        static auto instance = std::make_unique<singleton>();
        return *instance;
    }
};
int main() {
    auto inst1 = singleton::getInstance();
    auto inst2 = singleton::getInstance();
    cout << &inst1 << endl;
    cout << &inst2 << endl;
    return 0;
} 

It prints:

0x7ffcd729efd8
0x7ffcd729efd0

inst1 and inst2 are of different address, meaning I'm creating a new object each time I call getInstance(), so it's not a real singleton?

Why different address? I think inst1 and inst2 points to same object! Would you help to explain it?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 2
    `getInstance()` does return the same object every time. But you create different copies of that in `inst1` and `inst2`. `auto& inst1` would create a reference. – Yksisarvinen Sep 25 '22 at 12:06
  • The class still has implicitly generated copy constructor that can be used to copy the objects which you do when creating `inst2`. – Jason Sep 25 '22 at 12:06
  • 1
    You need to make `singleton` non-copyable. – Some programmer dude Sep 25 '22 at 12:06
  • Possible duplicate: [Why it does not declare a reference type if 'auto' var is initialized using a function returning reference?](https://stackoverflow.com/questions/45481105/why-it-does-not-declare-a-reference-type-if-auto-var-is-initialized-using-a-fu) (but I'm not sure if this is really the source of confusion here or not). – Yksisarvinen Sep 25 '22 at 12:09
  • btw `instance` is not a static member of the class. – 463035818_is_not_an_ai Sep 25 '22 at 12:10

1 Answers1

1

The class has implicitly synthesized copy constructor singleton::singleton(const singleton&) that is used when creating inst2.

//this is copy initialization
auto inst2 = singleton::getInstance(); //works because of accessible copy ctor

Same goes for inst1.

You can use auto& to create an lvalue reference(alias) or make the class non-copyable.

Jason
  • 36,170
  • 5
  • 26
  • 60