+ 2

Singleton class with Shared_Ptr

Hi Please refer below code which works okay with row pointer. Changing it to shared_ptr throws error. Can anyone suggest how to do the same? https://code.sololearn.com/cBOZ4ZnFrmQe

17th Aug 2021, 9:18 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
9 Antworten
+ 2
Ketan Lalcheta The error you're getting is occurring simply because of the use of make_shared. make_shared() uses placement new in order to construct the object in-place, within the storage space that was allocated. But in the context of this placement new function, clsTest's default constructor is private and as such it can't create a clsTest object and hence the error. The solution? This is one of the rare cases where using make_shared won't work. Create a raw pointer first, then create a temporary shared_ptr and assign it to plsTest I.e clsTest *ptr = new clsTest; plsTest = shared_ptr<clsTest>(ptr);
25th Aug 2021, 12:22 PM
Anthony Maina
Anthony Maina - avatar
+ 1
Ketan Lalcheta I found what's the issue with your code! When you're using shared_ptr, it uses the defaulted constructor for initialization(which is private). That's why your code produces error when you use shared_ptr, because it tries to use the default constructor but it's private. When you use operator "new", you're only allocating memory and not initializing it. Refer my following code. So, I think that's the issue with your code. Or am I wrong? https://code.sololearn.com/c481xubVymCL/?ref=app
17th Aug 2021, 11:18 AM
Rishi
Rishi - avatar
+ 1
You are correct. It calls constructor and it is private...but in my case, private should not be issue because I have created object in class method only unlike you ...nothing wrong in it.but my concern is that constructor should be private only... This prevents someone calling constructor to create object again and again... If I don't use smart pointer, it is my responsibility to release the memory. That's why I need smart pointer and private constructor
17th Aug 2021, 2:37 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta yes I searched the internet for singleton class and I found it. So, let's wait for someone who knows this concept well, to answer :)
18th Aug 2021, 1:22 AM
Rishi
Rishi - avatar
+ 1
Atlast, someone answered your question
25th Aug 2021, 12:44 PM
Rishi
Rishi - avatar
+ 1
27th Aug 2021, 1:25 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Your code worked fine when I made all the conductors public
17th Aug 2021, 10:51 AM
Rishi
Rishi - avatar
0
Yeah that's true.... But that is not what singletone is... Constructors should be private only... It is working when row pointer is there, but not once smart pointer is used
17th Aug 2021, 10:52 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta I don't know where the error is. But when I run this in my compiler which presents errors more beautifully, it said that the explicitly defaulted constructor was implicitly deleted
17th Aug 2021, 11:00 AM
Rishi
Rishi - avatar