You're leaking the memory assigned to _instance. You have to mention how you will free the singleton class object. It cannot be done with the destructor, is a very important point. All in all, the explanation is haphazard. The explanation is acceptable for a newbie. From interview perspective for a skilled professional, the interviewers will reject the candidate within a moment.
Great video! however, you have a memory leak as you didn’t free the pointer at the end of the program. This design is error prone as it relies on the user to free the pointer. To solve the problem you might use a shared pointer instead of a raw pointer.
Thanks for video. Can you please help me with below questions. 1. I don't see destructor in your video. Do we really need a destructor in Singleton pattern ? 2. Can we implement reference counting mechanism in singleton. If so please share the use case/example. I think destructor should have role here.
Hi venugopalreddy gopu, Nice questions. 1. You can keep destructor in singleton but you know one implements destructors for types which gets created and die in between your programs life[start-end], but singleton gets created in your program some where doesn't matter but stays there for ever till your program is running. And here comes the real fun with memory leak thing: When your program goes out of scope most probably all OS (Windows, Linux, Solaris..) keeps track of all the memory allocated to a process, and will free it when that process terminates, this was just for your knowledge i am not encouraging NO destructor singleton implementation :D. 2. I think no need to count reference because you should not make any copy of singleton object, that is what this singleton thing is all about.(always get the fresh object by calling static method of singleton class), because if you will keep copies then which one is the original one? Reason for creating singleton is: There is a requirement that we need to have only one object of that type throughout our program and if anyone wan't to change they will change that single object. (That single object will work as global data to your program) Please ask if any question. And i think i should upload singleton with more clear picture and keep destructor and private constructors, i missed in this video, i apologies for that.
Very well explained!! Couple of things I have observed: 1). Copy and assignment operator not mentioned under private section. 2) Source code link not found in the description section. Thanks in advance!!
Спасибо, все понял. Смотрел видео от своих соотечественников - ничего не понял. Языка английского не знаю, но этого парня понял лучше, чем рускоязычного.
I don’t know if this is standard practice but sometimes my singleton loads a bunch of data into memory, but I want it to load when needed as opposed to when the program starts. I have all the data in a std::unique_ptr member (normal variable, not static) that points to a struct. I have isLoaded() that returns true whenever the pointer isn’t null and a load() that gets automatically called by getInstance() e.g. If ( ! isLoaded() ) load(); Then I just have a freeMemory() static function that gets called by a separate garbage collector class that calls the equivalent function for every singleton of this type in my program.
Nicely explained Rupesh thanks a lot. Also your all other videos I see from long time and it helps a lot . Also can you make video on thread safe singleton design pattern.
Question : _instance is a private member, how come you are able to allocate memory directly ? or Is the access specifier nullified if its a static member / function in a class ?
Hi,I have one doubt why we are returning class pointer type for both the static member variable and static method .Could you please clarify my doubt. Thanks in advance...
_instance being a private member and a static at the same time seem to be conflicting to each other. The fact that you can assign a value of nullptr to it directly seems to be conflicting the private access modifier. In this case, it doesn't matter whether or not it is a private.
But why do we need a copy constructor and assignment operator? We are dealing with class pointers only and the real purpose of singleton DP was to have only one instance with client not getting any real handle to create objects, instead it is getting pointer to an object created only once. Correct me if I am wrong..
snehashish paul Hi.. You are right, we don't need them that is the reason vipul mendapara, asked me why did i forgot to include them in private section, because if will not move them in private section then compiler generated copy constructors and assignment operator will be in public section and they would allow your object to get copied.
+sunil singh hi.. very nice question, assume there is pool of objects which contains already built objects when your program needs any object then it will take from that pool and once done will return that object to the pool. And same for thread pool there you will have threads in the pool. if you need some thread take it from the pool and once done with thread return to the pool. And one thing which you might be knowing... that we create pool of those things which is valuable resource and creating them will take long time. so if you will keep a pool of such things and when ever needed you take it from there but don't destroy after using it, simply keep it in pool next time when needed dont create again just take it from the pool.. hope helped !!
Suppose, I have a friend class to the singleton class. By friends property, it will be able to access the private data members and functions. So it will be able to access the private constructor and thereby new object instantiation might be possible. Is there any way to block this way of object instantiation as it defeats the total concepts of singleton design pattern. Expecting a reply if the question is relevant. Thanks in advance.
in C++, is there a way to check if this is the same object? hey, i have to say it was pretty impressive when you were able tp compile and run in one try. maestro. make me a maestro.
i see this pattern as a global variable. its a fancy way of saying global variable. is this one object per session or one object across all sessions? lets say 100 users log into FB. all these users have one instance of DB connection and one instance of log obj?
You forgot to put copy ctor and assignment operator in the singleton class design. Or, to avoid memory leak you can add move ctor and move assignment operator.
What is the actual reason behind defining the static variable *instance outside the class, I tried to define *instance = NULL inside the class where it is declared but returns error...
It is already lazy initialization. In getInstance() function we are creating object, this object will never be created until it is needed or to say until getInstance() is not called. (this concept is call lazy initialization)
You definitely know this design pattern. May be you can do better explaining it. If you took two or three examples to explain it that would have been better. Take one case of multi threading take one database case. I am not really convinced you need only one connection instance to database. What if I need to update database once every four hours? Why would I keep an instance around? You can argue with me here on it if you want. Thanks.
Interesting comment, answer for data base question: we keep data base instance one to avoid race condition. i will upload multi-threading example some day for sure.. and plz do comment if you have any difficulty to understand part of the video.
Hi Rajesh, Actually it becomes little tough for some people to understand locking mechanism, so i thought i will include that in another part of this video, but still haven't got enough time to look back to this topic. Will try to covert that part ASAP. Thanks for reminding the point here. :)
The problem here is that there should have memory leakage. The object can be never deleted, never deallocated. You can use smart pointers (shared_ptr and weak_ptr) for resolve this big problem.
Hi, Your thinking is correct, and i am giving one more solution to this problem if someone don't know the use of smart pointers. Solution: Include this function inside your class. static void resetInstance() { delete _instance; _instance = nullptr; } This is equal to getInstance function, but this will delete the pointer we created and we won't have memory leaks. The only point is you will have to remember this and call only when you are leaving the program, is that at the end of main function, otherwise there will be many construction and destruction and you will lose your state in b/w. Nice point to discuss i should include this in some video, thanks for pointing out this.
yes, that's correct. There is many singleton design pattern, an other one is to use static class also. By the time, smart pointers resolve many problems and it is easy to implement. With singleton, use of smart pointer absolutly need to use weak_ptr also... if you want the code, i can give you one. But actually, most of devs are thinikng that singleton most of the time is not great t use due to problem with threads. Lot of them said that it is a bad design pattern. Actually, i'm using it, but i'm looking for an other way to design my code without singleton.
Nothing is bad if you know what you are doing and what is your scope, that would be foolish if some tell hypothetically about the problem you have in YOUR hand, THEY DON'T KNOW YOUR PROBLEM. Yes it makes problem when it comes to threading but there are solution to that as well, i often see getSingleInstace() in my project and we didn't need threading involved so we have singleton without thread safety. So go for it, after looking at all the possibilities and choose whichever suits your need best.
Yes, i understand that. I have to ask you if you know some other technic(s) who should garanty unicity call of object and be safe when multi process ? For example, in my program, (it is a Qt GUI framework used), a window can use the singleton (two in fact: one for XML data wrapper, one for a specific Potsgresql database access for general datas embeded), and call an other dialog box who can also use it in the same time (in parrallel) so... it is not a thread call directly, but it has to be use the same singleton at the same time... that could become a problem for me sometimes. I'm searching for ideas about that.
If you say "at the same time" then it is not thread safe. please look at these articles, might help you in that case. And sorry for dumping these many links, i did this because you know your problem better than me so you decide which is better solution to that problem :). Links: stackoverflow.com/questions/2576022/efficient-thread-safe-singleton-in-c www.codeproject.com/Articles/96942/Singleton-Design-Pattern-and-Thread-Safety www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf ruclips.net/video/c1gO9aB9nbs/видео.html&t=18m40s
#include using namespace std; class System{ private: static System *obj; public: static System &getInstance(){ static System theInstance; return theInstance; } void prn(){ cout
This is a very wrong implementation. The singleton object class must not create the instance itself. Just make the constructor public (with NULL assertion), and nullify the instance pointer in destructor... Then create the singleton instance on the stack in main() just before it is first used. Then there will be no memory leak and you will have your singleton easily testable (by inheriting a mocked version) and creating a scope limited fresh new instance of the singleton in every unit test. Simple and elegant. All the criticized problems of singleton will be gone (except for multithreaded R/W access - but you better should not use singleton then).
Hi Vladimir, i got the point but how would you have single instance through out the application. As you will create object on Stack, it will call destructor as it goes out of scope and next time you need it you will have to recreate it again (you have lost the previous state of the object which is important). Singletons are meant to store information through out the life time of the application.
Hi everyone, Don't forget to hit LIKE and SUBSCRIBE button for more videos like this!!
And this will help me a-lot.
Sorry for that..
You're leaking the memory assigned to _instance. You have to mention how you will free the singleton class object. It cannot be done with the destructor, is a very important point.
All in all, the explanation is haphazard.
The explanation is acceptable for a newbie. From interview perspective for a skilled professional, the interviewers will reject the candidate within a moment.
i am addicted to your videos. i am a Cppjunkie.
Great video! however, you have a memory leak as you didn’t free the pointer at the end of the program. This design is error prone as it relies on the user to free the pointer. To solve the problem you might use a shared pointer instead of a raw pointer.
Yes you are correct.
Thanks for video. Can you please help me with below questions.
1. I don't see destructor in your video. Do we really need a destructor in Singleton pattern ?
2. Can we implement reference counting mechanism in singleton. If so please share the use case/example. I think destructor should have role here.
Hi venugopalreddy gopu, Nice questions.
1. You can keep destructor in singleton but you know one implements destructors for types which gets created and die in between your programs life[start-end], but singleton gets created in your program some where doesn't matter but stays there for ever till your program is running.
And here comes the real fun with memory leak thing: When your program goes out of scope most probably all OS (Windows, Linux, Solaris..) keeps track of all the memory allocated to a process, and will free it when that process terminates, this was just for your knowledge i am not encouraging NO destructor singleton implementation :D.
2. I think no need to count reference because you should not make any copy of singleton object, that is what this singleton thing is all about.(always get the fresh object by calling static method of singleton class), because if you will keep copies then which one is the original one?
Reason for creating singleton is: There is a requirement that we need to have only one object of that type throughout our program and if anyone wan't to change they will change that single object. (That single object will work as global data to your program)
Please ask if any question.
And i think i should upload singleton with more clear picture and keep destructor and private constructors, i missed in this video, i apologies for that.
what a great way of teaching thank you sir for this wonderful helping video for my exams preparation.
Glad could help.
Very well explained!!
Couple of things I have observed:
1). Copy and assignment operator not mentioned under private section.
2) Source code link not found in the description section.
Thanks in advance!!
Thanks for pointing out that man. like is updated.. :)
superb explanation of the design pattern .
Source code with some variations.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class GameSetting {
private:
static GameSetting* _instance;
int _brightness;
int _width;
int _height;
GameSetting(): _width(567), _height(34), _brightness(53) {} // constructor is private
public:
static GameSetting* getInstance() { // static function
if(_instance==NULL)
_instance = new GameSetting();
return _instance;
}
int get_brightness() {
return _brightness;
}
int get_width() {
return _width;
}
int get_height() {
return _height;
}
void set_brightness(int _brightness) {
this->_brightness = _brightness;
}
void set_width(int _width) {
this->_width = _width;
}
void set_height(int _height) {
this->_height = _height;
}
void display() {
cout
Really great video!
More, all your videos are really good!.
All your videos goes straight to to point.
Why so little people have liked your video?
Thanks dude..
Really good video. I was searching for a good design patterns video lecture for months. Keep uploading more.
Thanks.. glad could help..
Спасибо, все понял. Смотрел видео от своих соотечественников - ничего не понял. Языка английского не знаю, но этого парня понял лучше, чем рускоязычного.
Superb sir....I must say u have awesome teaching skills
Thanks!!
your explanations are simply awesome bro...
Thanks bro..
Thanks roopesh. I always respect your explanations 👋.
Thanks man..
Great explanation thank you so much
but you forgot to delete the pointer
Yes, you are right.
Thanks you ! This video actually help me a lot ! Keep going
Glad it helped!
I don’t know if this is standard practice but sometimes my singleton loads a bunch of data into memory, but I want it to load when needed as opposed to when the program starts. I have all the data in a std::unique_ptr member (normal variable, not static) that points to a struct. I have isLoaded() that returns true whenever the pointer isn’t null and a load() that gets automatically called by getInstance() e.g.
If ( ! isLoaded() ) load();
Then I just have a freeMemory() static function that gets called by a separate garbage collector class that calls the equivalent function for every singleton of this type in my program.
Nicely explained Rupesh thanks a lot. Also your all other videos I see from long time and it helps a lot . Also can you make video on thread safe singleton design pattern.
Sure dude..
Other people are also asking for it.
@@CppNuts thanks....
Just wanted to know where we are deleting the instance which we made in the static function?
Hi you are doing great jobbb........................Please make some video on Multithreading ..........
sure dude wait for some time..
Question :
_instance is a private member, how come you are able to allocate memory directly ?
or
Is the access specifier nullified if its a static member / function in a class ?
nice video .. !
Game setting .. Hotkeys setting is good example.
Thanks man 😊
Hi,I have one doubt why we are returning class pointer type for both the static member variable and static method .Could you please clarify my doubt. Thanks in advance...
Thanks a lot,by seeing ur video got clear understanding over singleton design pattern.
Hello sir.. r u a software engineer in c++... u r following naming conventions... would u please explain how to follow naming conventions in c++
what is static methods? Purpose of using it?
_instance being a private member and a static at the same time seem to be conflicting to each other. The fact that you can assign a value of nullptr to it directly seems to be conflicting the private access modifier. In this case, it doesn't matter whether or not it is a private.
the video is great , but be careful with heap , you forgоt a delete operator . please be careful or use smart pointers
I am planning to create new video, i did so many mistakes in this.
you did not add copy constructor and assignment operator in private area. is it intentional?
just forgot to mention that.. thanks for informing.
But why do we need a copy constructor and assignment operator? We are dealing with class pointers only and the real purpose of singleton DP was to have only one instance with client not getting any real handle to create objects, instead it is getting pointer to an object created only once.
Correct me if I am wrong..
snehashish paul Hi..
You are right, we don't need them that is the reason vipul mendapara, asked me why did i forgot to include them in private section, because if will not move them in private section then compiler generated copy constructors and assignment operator will be in public section and they would allow your object to get copied.
ok, great.. Thanks to you for starting this C++ series.
snehashish paul Hi..
glad you liked it.
Sir please explain threadpool in detail will be very grateful to u .
Thankyou for explaination sir
Sure man....
Need some explanationa on object pooling and thread pooling.
At the end of program can i use this code:-
delete GameSetting::getInstance();
+sunil singh hi..
very nice question, assume there is pool of objects which contains already built objects when your program needs any object then it will take from that pool and once done will return that object to the pool.
And same for thread pool there you will have threads in the pool.
if you need some thread take it from the pool and once done with thread return to the pool.
And one thing which you might be knowing... that we create pool of those things which is valuable resource and creating them will take long time. so if you will keep a pool of such things and when ever needed you take it from there but don't destroy after using it, simply keep it in pool next time when needed dont create again just take it from the pool..
hope helped !!
we need copy constructor too? correct me if I am missing something here
No, it should be private or assigned with delete.
Excellent, Thank you very much.
Glad it was helpful!
Thank You for the clear explanation ... :)
+Sriraam M hi...
you are welcome.. :)
Suppose, I have a friend class to the singleton class. By friends property, it will be able to access the private data members and functions. So it will be able to access the private constructor and thereby new object instantiation might be possible. Is there any way to block this way of object instantiation as it defeats the total concepts of singleton design pattern. Expecting a reply if the question is relevant.
Thanks in advance.
may be you should need to print address to show object is not created again. And by the way video is still worth it.
Thanks a lot. You have got very good explanation skills. Amazing job.
Thank you so much..
Need to delete the copy constructor. Otherwise the singleton instance can be copy initialized
Correct!!
Do not we need private assignent operator and copy constructor for a singleton Class?
Yes we need that..
in C++, is there a way to check if this is the same object? hey, i have to say it was pretty impressive when you were able tp compile and run in one try. maestro. make me a maestro.
Practice!!!
maybe compare the pointers?
Good video..... Sir Please make a thread safe singleton pattern c++ video.
Sure dude..
Plz sir make the videos on thread safe
nice video with good example keep it up .
Thanks dude.
Thank you very much. Lord save you.
Thanks dude..
Global access and ownership, it may be disadvantage because anyone can modify, right?
Why do you consider this a disadvantage?
I see difference in your voice:) but not in teaching style its great
Thanks..
i see this pattern as a global variable. its a fancy way of saying global variable. is this one object per session or one object across all sessions? lets say 100 users log into FB. all these users have one instance of DB connection and one instance of log obj?
You forgot to put copy ctor and assignment operator in the singleton class design. Or, to avoid memory leak you can add move ctor and move assignment operator.
What is the actual reason behind defining the static variable *instance outside the class, I tried to define *instance = NULL inside the class where it is declared but returns error...
ruclips.net/video/EZMJmr3HVC8/видео.html
you will get your answer here.
Looks like addresses of both the setting objects are different.
You forgot to explain about Lazy Initialization in singleton. can you please explain w.r.t to code?
It is already lazy initialization. In getInstance() function we are creating object, this object will never be created until it is needed or to say until getInstance() is not called. (this concept is call lazy initialization)
Thank you.. understood clearly. One help! kindly make video on virtual function with diagrams using vtable and vptr w.r.t code in c++
sure will do it..
@@CppNuts Still waiting for this video.
i need a code but when i go through code link, its something else.please help i have study other patterns as ell this is first one
Here you will get all.
github.com/7yadavrupesh/designpattern?files=1
Thread pool not understood please share a useful link.
Why the object is not created using new keyboard
Can u share link for source code. I can't get source code from above mentioned link
Bro which Linux distro are u using????
Hi it is kubuntu 12.
You definitely know this design pattern. May be you can do better explaining it. If you took two or three examples to explain it that would have been better. Take one case of multi threading take one database case. I am not really convinced you need only one connection instance to database. What if I need to update database once every four hours? Why would I keep an instance around? You can argue with me here on it if you want.
Thanks.
Interesting comment,
answer for data base question: we keep data base instance one to avoid race condition.
i will upload multi-threading example some day for sure..
and plz do comment if you have any difficulty to understand part of the video.
Can these slides are available?
You don't delete the pointer?
Yaa that’s a mistake.
nice one !!
Thanks
am rewatching it !! :)
Videos please ..... nowadays you are not uploading videos
I am in my hometown, and things are not in my favor.
Going back to Banglore on 7th then you will see new videos.
can u make a good program on inheritance
Working on C++ Programming Series, will be available soon.
Use nullptr instead of NULL
Correct!! Thanks..
somebody read a lot of Scott Meyers' books :DD
+Fixpont i like him so much..
But never got the chance to read the books.
This code is giving segmentation fault. why?
#include
using namespace std;
class Singleton
{
static Singleton* instance;
int width;
int height;
int brightness;
Singleton():width(23),height(34),brightness(83){}
public:
int getWidth()
{
return width;
}
int getHeight()
{
return height;
}
int getBrightness()
{
return brightness;
}
void setHeight(int h)
{
height=h;
}
void setWidth(int w)
{
width=w;
}
void setBrightness(int b)
{
brightness=b;
}
static Singleton* getInstance()
{
if(instance==NULL)
{
instance=new Singleton;
return instance;
}
}
void display()
{
cout
Hi Ravi, i tested your code but it is not seg fault for me here.
But while running this code online I am getting segmentation fault
Here given design is not thread safe what is the reason you haven't considered that point ?
Hi Rajesh, Actually it becomes little tough for some people to understand locking mechanism, so i thought i will include that in another part of this video, but still haven't got enough time to look back to this topic. Will try to covert that part ASAP.
Thanks for reminding the point here. :)
Missing const for getters
Thanks.
Please create a Discord Server for us!! 🙏🙏🙏
I am not able to access the cppnuts.com website
I have shut it down.
@@CppNuts Will it be open again?
I am thinking of making another website, may take time.
I am wondering who will delete the _instance, otherwise it will have memory leak
That is another topic how to delete singleton pointer, please google it you will get so much of information
You can literally leave it to os..since the pattern is used mostly for heavy objects...
The problem here is that there should have memory leakage. The object can be never deleted, never deallocated.
You can use smart pointers (shared_ptr and weak_ptr) for resolve this big problem.
Hi, Your thinking is correct, and i am giving one more solution to this problem if someone don't know the use of smart pointers.
Solution: Include this function inside your class.
static void resetInstance() {
delete _instance;
_instance = nullptr;
}
This is equal to getInstance function, but this will delete the pointer we created and we won't have memory leaks.
The only point is you will have to remember this and call only when you are leaving the program, is that at the end of main function, otherwise there will be many construction and destruction and you will lose your state in b/w.
Nice point to discuss i should include this in some video, thanks for pointing out this.
yes, that's correct.
There is many singleton design pattern, an other one is to use static class also.
By the time, smart pointers resolve many problems and it is easy to implement. With singleton, use of smart pointer absolutly need to use weak_ptr also... if you want the code, i can give you one.
But actually, most of devs are thinikng that singleton most of the time is not great t use due to problem with threads. Lot of them said that it is a bad design pattern. Actually, i'm using it, but i'm looking for an other way to design my code without singleton.
Nothing is bad if you know what you are doing and what is your scope, that would be foolish if some tell hypothetically about the problem you have in YOUR hand, THEY DON'T KNOW YOUR PROBLEM.
Yes it makes problem when it comes to threading but there are solution to that as well, i often see getSingleInstace() in my project and we didn't need threading involved so we have singleton without thread safety.
So go for it, after looking at all the possibilities and choose whichever suits your need best.
Yes, i understand that.
I have to ask you if you know some other technic(s) who should garanty unicity call of object and be safe when multi process ?
For example, in my program, (it is a Qt GUI framework used), a window can use the singleton (two in fact: one for XML data wrapper, one for a specific Potsgresql database access for general datas embeded), and call an other dialog box who can also use it in the same time (in parrallel) so... it is not a thread call directly, but it has to be use the same singleton at the same time... that could become a problem for me sometimes.
I'm searching for ideas about that.
If you say "at the same time" then it is not thread safe. please look at these articles, might help you in that case. And sorry for dumping these many links, i did this because you know your problem better than me so you decide which is better solution to that problem :).
Links:
stackoverflow.com/questions/2576022/efficient-thread-safe-singleton-in-c
www.codeproject.com/Articles/96942/Singleton-Design-Pattern-and-Thread-Safety
www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
ruclips.net/video/c1gO9aB9nbs/видео.html&t=18m40s
This will not be threadsafe. Use a mutex to guard around the NULL check and object creation part
Thread safe is another topic.
#include
using namespace std;
class System{
private:
static System *obj;
public:
static System &getInstance(){
static System theInstance;
return theInstance;
}
void prn(){
cout
This is a very wrong implementation. The singleton object class must not create the instance itself. Just make the constructor public (with NULL assertion), and nullify the instance pointer in destructor... Then create the singleton instance on the stack in main() just before it is first used. Then there will be no memory leak and you will have your singleton easily testable (by inheriting a mocked version) and creating a scope limited fresh new instance of the singleton in every unit test. Simple and elegant. All the criticized problems of singleton will be gone (except for multithreaded R/W access - but you better should not use singleton then).
Hi Vladimir, i got the point but how would you have single instance through out the application.
As you will create object on Stack, it will call destructor as it goes out of scope and next time you need it you will have to recreate it again (you have lost the previous state of the object which is important).
Singletons are meant to store information through out the life time of the application.
so many adds, kiled my intrests
Sorry for that..