SINGLETONS in C++

preview_player
Показать описание


This video was sponsored by Hostinger.
Рекомендации по теме
Комментарии
Автор

I'd really like more of such design pattern content. Big fan btw, great content.

neerajbute
Автор

There is one important functional difference between a namespace and a singleton class. In a namespace, all of the data is initialized/loaded into memory when the program first starts; this might be undesirable sometimes when we don't want all the data initialized until we actually need it. In contrast, singleton instances are only loaded during the first call to the "Get()" method.

srijan
Автор

Great content from an experienced developer. I would note that technically there's a little functional difference between static member variables and local static variables. When you moved the static inside the Get() function, you made the initialization order deterministic. Local static variables are initialized the first time control passes through the declaration. This makes it safe to call one singleton from another singleton. Also local static variables are thread-safe beginning with C++11 (except when --fno-threadsafe-statics is used in GCC). Plain old static member variables aren't thread safe, and the undefined initialization order causes a nightmare situation. This is less of an issue with ints and floats, but if a singleton contains a class, like a string, you're in a really big trouble. Especially when you're using one singleton/static from the constructor of another singleton/static, and you have no way of knowing which one gets initialized first, and if you're out of luck. You may be using a variable that hasn't even been constructed or assigned yet. The destruction order is an even bigger mess than the initialization order, so stay away from custom destructors that rely on other statics. The object being destructed may be using an object that has already been destructed earlier.

tamasdemjen
Автор

A Log Class is a good example of a singleton. You just need a way to log things so you instantiate the Log singleton and can do Log.warning("something"). Other examples are in plugin architectures where a singleton can act as an API interface. You want to provide a certain class of functionality, then there is a singleton for that and you bind to it by registering handlers etc.

NicolaiSyvertsen
Автор

Yes! Please, do cover more Design Patterns!

Side question: can you type and talk like that or is that edited? Regards!

Idlecodex
Автор

Great Video. First ran across singletons on a Java project (where, as you point out, everything is a class). Since then, used it occasionally if needed to reuse some object that was 'expensive' to create. One was where a lengthy connection to another server database had to be established. Each query on the object was stand-alone, but creation took time. So we created once in a singleton and then all the code could 'get' and 'query' without having to recreate the connection all the time.

mikefochtman
Автор

I am so damn happy this series is back. Have been waiting for a c++ video for so long!!

sriramiyer
Автор

One use case for C++ singleton that makes sense to me is the case where you have several classes with a common base class. Each of the derived classes could be a singleton, benefiting from reused code and encapsulation and they're similar enough to where it makes sense to derive them all from a single base virtual class. In this case, the base class takes care of most of the structure - making it reusable. Then the singleton derived classes have just a few minor differences for each of their use cases.

philmarsh
Автор

Keep it up, i am a student that is c++ geek. I learnt a lot through you.

kashish
Автор

more design patterns please!! you're by far the best C++ teacher on yt

essmunson
Автор

Cherno, have you considered covering more design patterns in the C++ series? Thanks!

gustavoleite
Автор

You forgot to mention the most important thing.
It's a antipattern and should not be used except few rare exceptions.

It adds hidden dependencies into the whole codebase, makes unit testing harder and causes lots of pain and costs few years later.

stke
Автор

This is HUGE in embedded programming because we have to often interface with C libraries. The singleton pattern allows us to interface with C callbacks but still use dependency injection for unit test.

I love your videos. You are doing this right. C++ is the best language ever made and you are making this accessible

adamjcasey
Автор

Dare I say, your playlist of C++ videos are the best in the universe so far, youtube aside. I can not thank you enough. If I had the financial ability, Id definitely join the patreon group, not for the extra access but just to show my support for the greatest C++ videos on the net. Who knows, maybe I will get there soon.

gmcquads
Автор

Me and my friend had to give a 40 minute presentation about the Design Pattern, specifically using C++ as well.

Singletons are, from what we've seen most of the time disliked and sometimes treated as an anti-pattern even. Now, Singletons do have their limited uses, so there's that. But how to construct one and especially how to destruct one or worse, doing that AND being in concurrent environment, that is a real piece of work.

What Cherno did in construction was a Meyers Singleton, i.e. the local static one. There's also the way of allocating the singleton on a heap and checking if the pointer is null and if so, creating the Singleton, otherwise just returning the pointer as a reference.

Threading usually involves something like double checked locking (you don't want to construct two singletons, that'd defeat their purpose) or something that ensures a single call of the constructor.

Destruction is pretty funny too - you can either ignore possible problems or think of the Keyboard-Display-Logger problem and think of the Phoenix Singleton (where you basically remake the Singleton anew) or the Longevity Singleton, which requires a lot more work.

If someone has a need to know more about Singletons, I recommend Modern Design Patterns in C++ or the original Design Patterns by GoF.

Tbh, once we did that presentation, I started to see Singletons a lot more. E.g. my browser uses files to lock the processes and guess what, that's a Singleton. Never seen it before the presentation.

Goras
Автор

Thanks cherno for all these videos. I binge watched you whole series almost a week ago so that I can be comfortable with c++ again(even more now). It really helped me to understand c++ codebase of mlpack organization, I even made a PR on it which is almost accepted. Thanks a lot.

PrinceGupta-jolo
Автор

OMG, You're even married, Lol, Its been 7 years man, since I followed your channel and waited for you to release more videos, Youtube recommendations have brought us back together lol.

TheGenZProgrammer
Автор

I love your video. Some explanations (e.g. the linkedin explanation ) are confusing because they use complicated classes as their demo. I really liked how you didn't bother making a working random generator function and focused on singletons!

kristystrives
Автор

Loving the content! Could you possibly do a video on iterators? As far as what they are, how you can use them in a queue/linked list implementation, etc

xdestyn
Автор

We use a lot of static function variables in methods especially for fixes that should not break ABI (Introducing variables or reordering may break ABI).
The best advantage from this approach is the guarantee for MT safety when initialization the variable - either better if the variable is a class.

Something you didn't mention (Or I missed it) is MT thread safety which is the crucial point for singleton initialization.
(Refers to the famous double-if-lock pattern).

TNothingFree