0

Why to have private copy constructor in singleton

Hi We need to have copy constructor and constructor along with assignment operator as private member for singleton class Why below code displays same address for both the pointers ? I havent made copy constructor private, but it still works as per expectation of singleton... Am i missing something ? https://code.sololearn.com/c45wU4TYofDf/?ref=app

6th Jul 2022, 3:58 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Respostas
+ 2
You are not calling any kind of copy constructor of singleton here. on line 27 : "singleton* p2(p1);" you are simply creating another pointer (p2) pointing to the instance of singleton pointed by (p1), there is still only one instance of singleton class existing in the program, there are only multiple copies of pointers pointing to that same instance.
8th Jul 2022, 8:03 AM
Arsenic
Arsenic - avatar
+ 1
p1 and p2 are variables stored in stack, with values as addresses from heap. In your code you initialize p2 with the value of p1. They both point to the same address in the heap memory. That's why they output the same address.
7th Jul 2022, 3:51 AM
Vasile Eftodii
Vasile Eftodii - avatar
0
That's correct But with this logic, dont we need to have private copy constructor for a full fledged singleton class ?
7th Jul 2022, 4:01 AM
Ketan Lalcheta
Ketan Lalcheta - avatar