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?
CodePudding user response:
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.