Local Static in C++
Вставка
- Опубліковано 30 лип 2024
- Twitter ► / thecherno
Instagram ► / thecherno
Patreon ► / thecherno
Slack ► slack.thecherno.com
In this video we take a look at yet another use of the static keyword in C++. Static can be used in a local scope to extend the lifetime of the variable to be essentially endless, rather than getting destroyed when the scope ends.
Static in global scope ► • Static in C++
Static in class scope ► • Static for Classes and...
Series Playlist ► • C++
BEST laptop for programming! ► geni.us/pakTES
My FAVOURITE keyboard for programming! ► geni.us/zNhB
FAVOURITE monitors for programming! ► geni.us/Ig6KBq
MAIN Camera ► geni.us/t6xyDRO
MAIN Lens ► geni.us/xGoDWT
Second Camera ► geni.us/CYUQ
Microphone ► geni.us/wqO6g7K
You intentionally added static noise in a Static video. A very nice touch. :P
Lol it's in the video, I thought it was my phone causing it.
Same xd
dude i actually unplugged my speakers wondering why it didn't stop
lol, maybe that was a plan :)
I think the initial implementation at 5:29 has bugs but the idea is clear. 👍
Aaah! The static background sound for a static episode. That’s some next level shit
Damn I was following pretty good up until the point he started talking about Singleton class. That was where my brain decided to shit itself seeing * and & at once
same here bruh...
my brain console get critical error in this example, [C0463] 'definition not found xD' -- FAILED
time to debuging...
e file mou apla perase to apo to debugger kai ola tha pane kala :D
This video has really cemented my understanding of static literally being used for 'static' data- it is for data where there is only one copy that is shared. In this case, that is important for creating variables that persist even after going out of scope when the function block ends, so that they can be incremented when the function is called again.
"static" has soooo many different meanings in C++ LOL
@المهاجر التونسي but you can create an alternative while still preserving the previous keyword.
Well, then get ready for const
Its just like gurls' 'hints'
Takeaways: static variable in a function can live outside the scope like global variables, but not be accessed from outside.
its no accurate. if you return a reference/pointer of that static variable from the function, than you can access it in other functions.
@@shalip No, because that's undefined behaviour. The C++ standard doesn't guarantee that the static variable will still exist after the function ends for the last time.
Edit: what I said is wrong. The lifetime of a static variable in a fumction in C++ is the lifetime of the program, not sooner.
It's still a bad idea though because of multithreading
@@ronensuperexplainer so just make sure "the function ends for the last time" situation is never reached by always calling the function again after each pointer use xD
@@shalip Direct accessing by '.' or '->' is not allowed. However, accessing by a public function is something else.
@@shalip by access if you mean to call its value and assign it to other, then you are right. Otherwise to change its content is not available at least as I just tried.
i like the phone static. nice touch ;)
Excellent - am loving your series! Love that you get right to the point.... this is a great reference for all these concepts.
Wow! I've been using c++ for 6 years and never knew you could use "static" at a local level like that. Thanks for the tips.
Same here. And I can count more than 15 years of c++ 😂
One place I've found this useful is in creating an object which for 'reasons' cannot be visible at class level, is expensive to do, but is the same every time. By making it static in a class method you remove it from the class level and only have to pay the initialisation cost once.
In my case this was the loading of a large file which I was going to need repeatedly, but other design considerations forced me to put it in the method rather than the class.
pls make a singleton video. i dont understand the tutorial once u start introducing singleton.
First of all: A Singleton is a class that just has one instance of itself. This is a useful software pattern, which is widely used. For example, imagine a game you are writing and you want to have something that keeps track of what your player does, that tracks where the user is going, etc. You just want one instance that tracks that exact data, because you don't want to track the same data twice. So, if you were to define a singleton within C++, you could do it the way it is represented in this video. Static within classes basically means: We are operating without instances of our class. If you were to use the defined Singleton class, you would call the Get()-method of the class, but you would not create a new instance of that class. That is the reason, why the "static Singleton instance;" variable is static, and this is why the "static Singleton& Get()" function is static aswell, because we are not accessing the function with an instance of the class, but through the scope-operator of C++, which is "::", "Singleton::Get().Hello();".
@@CMGBgamerz Thank u so much
@@eurko111
Ur just a hater
@@Pensive_117 r/bruh
Wut?
@@CMGBgamerz crack
Thanks for another awesome explanation!
Looks like this video didn't end up in the C++ playlist though, I almost missed it :P
I've just used local static as part of a Macro that generates static events for a class. It helped me avoid the definition in the .cpp file. Thanks once more Cherno!
Some mobile phone interference in this video. Everywhere, It's quite bad.
Had me excited there thinking that a text was incoming :D
Haha, happened to me too, then tried to mute sound on video....
I was about to comment, did you leave your phone or something with a high frequency radio next to your recording device?
1:28
1:56
2:12
4:22
You might say there is a bit of.... static.
.... crickets ....
i have a blue yeti and it does this all the time almost exactly can u please explain what is causing this and a possible remedy?
This is your 1st video that made me wonder a thing or two. My most important question could be put into three letters, but I try to achieve a bit more understandable form of my issue. :)
1:29 I though something was wrong with my speakers lol
Well Done Sir, short videos and to point.
Thanks for your hard work.
Thank you!! Great explanation as always :D I was going to say i got confused with the code you wrote at 4:55, in line 11 but in the process of trying to explain my doubt i clarified it for myself :)
Watch the video where he says about static in classes. Every variable you declare as static inside a class must be declared on the translation unit as well
type scope var name
Singleton* Singleton::s_Instance; // initialization is not important but good practice
Thank you for the help! That was exactly what i've done, i seeked for that video and watched it b4 asking because it sounded confusing for me ;D
Personal Notes:
- "A static local variable allows us to declare a variable that has the lifetime of essentially our program however its scope is limited to be inside that scope"
- void Func(){
static int i = 0;
i++;
std::cout
genius explanation and to the point
thank you so much The Cherno
You are beast at understanding cpp in a beginner friendly way.
Could you talk more about design patterns? I've read about a few but I'm interested to learn more
Oh that would be interesting to have his opinion on patterns and how they use them if they use them !
yes! that is basically my biggest concern and when to use them.
did you find out if he made any?
@@shohamziner Hey bro! What about current situation? Did he make those videos about patterns?
@@medetkhanaltynbek1442 what about now ? did he make those videos or not ?
This is one of the best lecture in the series.
Now that it was explained correctly I can definitely see valid uses for this.
most amazing explanation I ever saw of static
Thanks! I was always afraid of using static variables like this because it seemed so unintuitive that the variable wouldn't be reset to 0 every time the function is called.
really useful for finite state machines!
Very good approach. Thank you
10 years programmer here and just learned that such tool exist! this is so powerful, it could've solved many problems for me
appreciate this series
really nice third video on this topic
This literally took me three times to understand what you were doing in singleton class!!!
It's pretty difficult for a beginner.
even more usage of the keyword "static" I didn't knew about! Even though it's a quite specific case that I won't use often I guess.. Still good to know in the back of my head :)
and yeah! you explained Singletons!
These are very clear explanations of subtle concepts. I'm concluding c++ is a difficult language to master. I can only imagine it takes many years to be proficient at developing large professional applications with c. I suppose the key advantage to c is being able to code closer to hardware, for speed-critical applications.
I haven't seen all your videos yet. But I am gonna go ahead and give this one the prize for coolest hair prematurely.
The first example of Singleton with static member variable would be returning NULL. So Singleton::Get().Hello() might be crashing. Please correct it.
May be it didn't crash as you did not access any member variables.
I like the way you give the gist of the concept in very less time. Keep doing it.🙏
5:23
Can anybody explain where exactly the 1st instance is created?
I could only see its intialized with nullptr.
He changed my generic definition for singleton class !
Nice tutorial :P
6:50 you forgot to cut lol
6:55 Glitch in the matrix
Man, you're simply the best
Hey, great video. Just one question. Isnt dereferencing a null pointer undefined behavior?
I think you should mention that {} creates a scope. (Or maybe you did that and I missed it). Nice vid, keep going :D
ohh!! it was his phone, moved my phone a series of time thinking I was the one causing the interference! :) Nice video
I spent 20 seconds adjust my headphone plug, checking any phone nearby. Still weird STATIC, I must pause the video to investigate further. Then there goes the "aha" moment.
I really like how you transitioned into the singleton implementation (this is also how Scott Meyers suggests it)
i think he was making it so that you didn't need to have the instance of the Singleton class within your scope in order to access it or manipulate it. the namespace of the Singleton class included a pointer to the only instance of the class, which was returned as a reference to the single instance of Singleton by dereferencing the pointer in the get() function, thus the instance can be accessed from anywhere in the program as the class was defined at a global level. at least that's what i surmised, i may be wrong :0
but in this manner as 5:53 shows, can we actually get two instances of singleton simply by defining two objects of that type? (because the default constructor isn't private)
Can you use the scope operator for a static variable inside a function like you did with a static struct member in the last video?
5:09 but because you set the class instance pointer to nullptr if you run it it will crash, right?
I might be wrong as this is the first I've heard of a Singleton class but am I right in thinking that the example Singleton class used here was incomplete in the fact that there was nothing in place to stop another instance being instantiated? Like, if there is no user defined constructor, what's to stop you from instantiating normally without using the Get() function, like this?:
Singleton a;
i understand that when static singleton instance is created with
static singleton s1;
return s1;
Here static object s1 is created in global/static memory and the reference of s1(some address) is passed using which member method of singleton class can be accessed.
whereas in 1st method @4:45 singleton* is created and it is initialized to zero
singleton* singleton::s_instance=nullptr;
so when de-reference the above pointer, the address it possess will be zero(dereferencing address zero ) and passing the reference of it.
1.can we de-reference address zero?
practically we are passing reference of value that we get after dereferencing zero....then how can we access the methods?
when i tried the code it compiles and works but id don't know how?
Do you have to delete the static variable explicitly when finished with it, or are you unable to and it "lives forever" (until your program ends)?
Where is the static variable or instance created ? on the heap or the class ? I am guessing it would be the stack here, but then it would be destroyed only at the exit of the program ?
Absolutely brilliant, regardless of the GSM interference humming noise in the video. I think you are a talented developer Cherno and, in my opinion, you should go back to work in the industry (EA or elsewhere) as a lead developer. You could have 2-3 developers under you command even at this young age.
Quick question - I have been just recently started learning C++ after working with Python for a while. I was curious if this course actually works any projects to develop skills? Also if there are any projects that you guys could recommend for a beginner?
Static variables inside scope of cfile scope are extremely usefull for embedded applications and for encapsulation of cfile, but global variables are like really dangerous in that sense - so in other words, I would encouarge to use static variables whenever you can especially in cfile scope not necessarily in a function scope (but use them if you need them) and use global functions as access to static data of the cfile ... it makes sense due to encapsulation of cfile as they now can be accessed as "objects" with internal hidden structure (static data and functions) and external functions to access functionality and internal data - but dont use global variables, it is just simply hazarduous and not clean and makes your code a garbage code.
Also if you make static variables make sure your Embedded device implements some kind of SecDed with ECC or some Error correction or at least Parity protection when accessing memory for values /contents of those variables for part of memory where thos static variables are located (.bss memory section usually or .ebss - old notation for uninitialized or 0 initialized and .data memory section for initialized static variables other than to 0) So those static variables wont get corrupted values over time because it may have error-cumulative effects on the device especially in automotive or aerospace applications.
If I want to change a functions behavior based on whether it's been called or not before, would this be the best way to do that? Or would there be a better way?
setting the singleton pointer to null results in an ub (undefined behavior) so we have to pass the instance's address
I think local statics could be handy in some cases for functions outside of a class. For class methods though, I think it would be better practice to put statics at the class level. No doubt, there are those rare use cases where static variables make sense in a class method. In your example of using a static singleton, I would prefer to have that at the class level too. Mind you, I haven't dealt with design patterns in C++ yet and perhaps your demo is standard practice. Still, it seems strange to me that there would be any lingering side effects remaining after a function returns. It's like, the scope of the function has ended, but there is still some connection in limbo. Hmmm...
I am really curious about how can you type that fast. Are you using short cut key word combination or do you speed up your video or just your typing speed is fast?? Could you also do tutorial about how to write code fast or trick to write code?? Thank you in advance :))))
So just a little confused if anyone could help. So the static version of "I" isn't getting reset to 0 every time because under the hood, it's getting checked to see if it already exists and if so it just moves on?
if I remove the & from the return type, it starts behaving like an instance method. Why ?
5:56 what happens if I do this:
static Singleton* instance = new Singleton
Then I delete the Singleton and run it again to see if it creates a new Singleton(again)
So what happens?
if I use Local Static in C++ variable will be destroyed when program execution but if we use new to create variable it will be forever except I used delete I'm right?
Funny video to put this comment on (given the editing skills you have also portrayed)..
You have a talent for describing what you talk about in an in-depth yet succinct and clear way. I appreciate you sharing that talent with us. 🤍
when we declare static variable in function then we don't need to initialize it outside of function ,but when we declared static variable in class ,then why it's necessary to initialize explicitly it outside of class.??
i dont get it how comes he was able to dereference a nullptr, he has assigned a null pointer to s_Instance, which means Get function will return a dereference to nullptr?
Amazing!!! 👍
Can someone explain why in this case, you don't need to define the static variable outside the scope. But in classes, you do need to?
Excellent
Dude just went back in time epic...
Oh he just forgot to put this before Static video.
I had to change position of my phone several times before noticing that the static was coming from video.
5:00 Can someone tell me why he is able to access s_Instance which is a private class variable?
Btw usually you declare a private constructor to prevent a developer from creating another instance of the Singleton.
I didn't know about locale static, but i just guess out and answered at code interview. Well, that just worked lol
Please do a full lesson on the singleton pattern. Every video I have watched on the matter has been way to long and does not get to the point. I feel if you were to do a brief 5 minute video on singletons my understanding of them would increase.
I wish you explained it a bit more like the :: and such... totally just jumped into that lol.
The basic incrementing example with the static value inside the function reminds me a lot of Python generators.
I recently just needed this functionality and wished it were possible however I was using java in LD39.
That singleton example was a good brain twister
Very awesome
At 4:54 when you return s_instance by dereferencing it, I wonder why compiler doesn't give an error since we are dereferencing a nullptr.
Also when I tried the same, but with return type of Get() func set to just Singleton instead of Singleton&, the compiler does throw an error stating that s_instance is a nullptr.
Can you explain if the reference return type of Get() func has someting to do with this?
my program crash when i tried to print dereferenced nullptr, moreover static data members and static methods of class can be accessed with pointer of type class which is nullptr
but if u try to access non static data members from nullptr it
will give error or crash and it should because they requires
object to be created for get called and static Fun/members does not
however a non static member function can be called with nullptr pointer variable
but the condition is it should not operate or use class members like if it was only printing hello world will work
Coming to your question
"explain if the reference return type of Get() func has something to do with this? "
yes it does have something to do with & as return type, if you MUST know what is Rvalues and Lvalues then
when you return *ptr as ( & ) as return type the actual VARIABLE *ptr is returned and accessing static function with *ptr VARIABLE which is nullptr in this case is valid
And when u return without ( & ) then only the value of variable *ptr(Rvalue) is returned which is nullptr in this case, thats why it doesn't work without ( & )
Cherno has a another video on singleton where he doesn't use pointers and that code makes a lot sense rather than this.
Can you explain the static at 1:30
i=0 is there in start of Function, why it is not setting it to 0 every time, when Function is called.
are you using vim keybindings? how did you copy it five times
I don't quite understand the singleton part. I still have a hard time understanding pointers and references. At the last example, what did the whole Static& Get() refer to? Where in memory did the reference look and find Get()?
Lets' say you're getting some data from an online database. You create a function that fetches that data and whenever you want to use that data you call that function and that function returns you an object that you can use. Now, imagine you want access to the data a 1000 times throughout your code. That function will make a 1000 requests to the database server to get data. That's an ineffective strategy for a few reasons:
1. It's increasing unnecessary amount of traffic that the server is getting.
2. There's usually a delay between a request being made and getting a response. In that delay, your application will just wait for the data and the user will have a blank screen.
A better solution will be a singleton class where once the class fetches data from the server, it stores its existence or instance in a static variable so that the data doesn't disappear even after the function returns. The get function is basically gonna check if the reference for the singleton class already exists in the memory. If it does, it just returns that instance of the Singleton class that holds the data.
The line Singleton::Get() is returning that instance that holds the data and Hello() is a method in that instance. Hopefully that helps.
So does this make memory to be allocated in the heap?
My employer should pay you for teaching me c++. On the job training was pretty lacking unfortunately 😂 but you come in clutch 🎉
Where are you getting paid to dev in c++ if you don't know it to this level? Not trying to be insulting, just curious. What's your pay like?
Can somebody please give me a good reason to use this? It seems like it would be easier and more clear to somebody else reading your code to just declare the variable outside the function.
6:07 Why is it a problem ? I tried and it works, is it a memory leak ?
(sorry if my english is bad I am french)
@Peterolen I understand, idk why but it works anyway, maybe an undetermined behavior
wouldn't we also need to make the default constructor inaccessible for singleton class?
This hair of yours is so damn crazy, I love it xD
Wow!. thank you.
First of all thank you for the great set of videos.
I think this video however is not telling the whole truth about static variable. I'm a C programmer learning C++. If static variables wirk the same way in C++ as they do in C then it might not be true that the variable is initialized when a finction is called for the first time (when declared within that function). It is initialized at the compile time and stored in the compiled program file. This can be easily verified by declaring a large static variable. If we see the executable file growing in size it means it contains that variable and it is initialized to the value of our choice already. If I'm correct then one should keep that in mind when declaring large static variables. One advantage is that those variables will be initialized at the compile time so your program will not waist time on that.
Please correct me if I'm wrong.
What does deleting a variable from memory actually mean?
Are the memory bits set to 0 or are they somehow just marked as free and can be overwritten when needed? Or something else?
Marked as Free
@@coenfuse so memory cells each have a marker register that holds the flag?
That last Singleton example made the tutorial.
static ia good for functions that repeat 100 times a second and make a variable each time static keeps it there
i thinking local static is useful , i made i c++ project in high , we weren't taught static at that time, i one of my function where i have to update somethin' i tried with declaring a global variable , but somehow messed up with everything , static could have definitely solved that problem. gonna try now,,
Thankx man
Is it stored in the heap?
Q1. why do u have get().Hello(); ? get() is a function not an object so why can a function accesses this Hello() function?
Q2. returning *s_Instance into reference get()? U dereference s_instance which is nothing, and u return nothing into the reference? and then get().Hello? I am so confused >
If a singleton is a class that can only be instaniated once, then why not just standard variables without a class, would that not achieve exactly the same thing?