+ 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
9 Respostas
+ 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);
+ 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
+ 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
+ 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 :)
+ 1
Atlast, someone answered your question
+ 1
Thanks Anthony Maina
0
Your code worked fine when I made all the conductors public
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
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