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

КОМЕНТАРІ • 298

  • @danielc4267
    @danielc4267 6 років тому +1100

    You intentionally added static noise in a Static video. A very nice touch. :P

    • @MsJavaWolf
      @MsJavaWolf 5 років тому +179

      Lol it's in the video, I thought it was my phone causing it.

    • @nathanpinard5132
      @nathanpinard5132 4 роки тому +10

      Same xd

    • @danieleccleston7928
      @danieleccleston7928 4 роки тому +42

      dude i actually unplugged my speakers wondering why it didn't stop

    • @alt0v14
      @alt0v14 4 роки тому +7

      lol, maybe that was a plan :)

    • @pitiren
      @pitiren 4 роки тому +4

      I think the initial implementation at 5:29 has bugs but the idea is clear. 👍

  • @DominicVictoria
    @DominicVictoria 6 років тому +106

    Aaah! The static background sound for a static episode. That’s some next level shit

  • @lukaspetrikas6320
    @lukaspetrikas6320 3 роки тому +62

    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

    • @quentinarrius
      @quentinarrius 3 роки тому +2

      same here bruh...

    • @E.Wolfdale
      @E.Wolfdale 2 роки тому +2

      my brain console get critical error in this example, [C0463] 'definition not found xD' -- FAILED
      time to debuging...

    • @memcpy7
      @memcpy7 2 роки тому

      e file mou apla perase to apo to debugger kai ola tha pane kala :D

  • @mattstyles4283
    @mattstyles4283 3 роки тому +25

    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.

  • @AlexP-ud5bu
    @AlexP-ud5bu 4 роки тому +165

    "static" has soooo many different meanings in C++ LOL

    • @oskarjung6738
      @oskarjung6738 4 роки тому +2

      @المهاجر التونسي but you can create an alternative while still preserving the previous keyword.

    • @bartekm3878
      @bartekm3878 3 роки тому +14

      Well, then get ready for const

    • @soham7510
      @soham7510 3 роки тому +4

      Its just like gurls' 'hints'

  • @rika9317
    @rika9317 4 роки тому +82

    Takeaways: static variable in a function can live outside the scope like global variables, but not be accessed from outside.

    • @shalip
      @shalip 3 роки тому +6

      its no accurate. if you return a reference/pointer of that static variable from the function, than you can access it in other functions.

    • @ronensuperexplainer
      @ronensuperexplainer 2 роки тому +1

      @@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

    • @DesyncX
      @DesyncX 2 роки тому

      @@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

    • @kioumarsbabakhani7547
      @kioumarsbabakhani7547 2 роки тому

      @@shalip Direct accessing by '.' or '->' is not allowed. However, accessing by a public function is something else.

    • @binyi1114
      @binyi1114 Рік тому

      @@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.

  • @ThunderBret1
    @ThunderBret1 6 років тому +65

    i like the phone static. nice touch ;)

  • @marcholman291
    @marcholman291 4 роки тому

    Excellent - am loving your series! Love that you get right to the point.... this is a great reference for all these concepts.

  • @wiiguy21
    @wiiguy21 4 роки тому +13

    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.

    • @sebastienalbert6159
      @sebastienalbert6159 8 місяців тому

      Same here. And I can count more than 15 years of c++ 😂

  • @ColinBroderickMaths
    @ColinBroderickMaths 3 роки тому +3

    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.

  • @97NJK
    @97NJK 6 років тому +184

    pls make a singleton video. i dont understand the tutorial once u start introducing singleton.

    • @CMGBgamerz
      @CMGBgamerz 5 років тому +150

      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();".

    • @eurko111
      @eurko111 5 років тому +6

      @@CMGBgamerz Thank u so much

    • @Pensive_117
      @Pensive_117 4 роки тому

      @@eurko111
      Ur just a hater

    • @eurko111
      @eurko111 4 роки тому +15

      @@Pensive_117 r/bruh
      Wut?

    • @alexcast1963
      @alexcast1963 4 роки тому +2

      @@CMGBgamerz crack

  • @TitusPeterson
    @TitusPeterson 7 років тому +4

    Thanks for another awesome explanation!
    Looks like this video didn't end up in the C++ playlist though, I almost missed it :P

  • @nahuelarjona
    @nahuelarjona 3 роки тому

    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!

  • @cybercat1531
    @cybercat1531 7 років тому +80

    Some mobile phone interference in this video. Everywhere, It's quite bad.
    Had me excited there thinking that a text was incoming :D

    • @oriyus
      @oriyus 7 років тому

      Haha, happened to me too, then tried to mute sound on video....

    • @ghostravenstorm385
      @ghostravenstorm385 7 років тому +2

      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

    • @ericc2662
      @ericc2662 7 років тому +24

      You might say there is a bit of.... static.

    • @cybercat1531
      @cybercat1531 7 років тому +3

      .... crickets ....

    • @Dragunovx2
      @Dragunovx2 7 років тому +1

      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?

  • @jannesopanen8032
    @jannesopanen8032 3 роки тому +1

    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. :)

  • @Ranakade
    @Ranakade 5 років тому +10

    1:29 I though something was wrong with my speakers lol

  • @jeffreypruitt3397
    @jeffreypruitt3397 3 роки тому

    Well Done Sir, short videos and to point.
    Thanks for your hard work.

  • @krec348
    @krec348 7 років тому +3

    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 :)

    • @marinosmanidakis9939
      @marinosmanidakis9939 7 років тому +2

      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

    • @krec348
      @krec348 7 років тому

      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

  • @serkanozturk4217
    @serkanozturk4217 Рік тому +1

    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

  • @sallaklamhayyen9876
    @sallaklamhayyen9876 2 роки тому

    genius explanation and to the point
    thank you so much The Cherno

  • @AfrinFoodVlog669
    @AfrinFoodVlog669 6 місяців тому +1

    You are beast at understanding cpp in a beginner friendly way.

  • @meh1672
    @meh1672 7 років тому +65

    Could you talk more about design patterns? I've read about a few but I'm interested to learn more

    • @Cynokine
      @Cynokine 7 років тому +13

      Oh that would be interesting to have his opinion on patterns and how they use them if they use them !

    • @amirbakz
      @amirbakz 6 років тому +4

      yes! that is basically my biggest concern and when to use them.

    • @shohamziner
      @shohamziner 3 роки тому +1

      did you find out if he made any?

    • @medetkhanaltynbek1442
      @medetkhanaltynbek1442 3 роки тому

      @@shohamziner Hey bro! What about current situation? Did he make those videos about patterns?

    • @jitendraraghuwanshi1365
      @jitendraraghuwanshi1365 2 роки тому

      @@medetkhanaltynbek1442 what about now ? did he make those videos or not ?

  • @aniketahir5578
    @aniketahir5578 4 роки тому

    This is one of the best lecture in the series.

  • @IllumTheMessage
    @IllumTheMessage 6 років тому +1

    Now that it was explained correctly I can definitely see valid uses for this.

  • @igniculus_
    @igniculus_ 6 років тому

    most amazing explanation I ever saw of static

  • @reubenfrench6288
    @reubenfrench6288 6 років тому +1

    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.

  • @nadnerb2178
    @nadnerb2178 4 роки тому +2

    really useful for finite state machines!

  • @hannesblack6949
    @hannesblack6949 7 років тому

    Very good approach. Thank you

  • @TheNorthRemember
    @TheNorthRemember 3 місяці тому

    10 years programmer here and just learned that such tool exist! this is so powerful, it could've solved many problems for me

  • @ZestyMuffins
    @ZestyMuffins 7 років тому

    appreciate this series

  • @BeatSmokerFactory
    @BeatSmokerFactory 5 років тому

    really nice third video on this topic

  • @pratham9705
    @pratham9705 2 роки тому

    This literally took me three times to understand what you were doing in singleton class!!!
    It's pretty difficult for a beginner.

  • @rcookie5128
    @rcookie5128 7 років тому

    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 :)

    • @rcookie5128
      @rcookie5128 7 років тому

      and yeah! you explained Singletons!

  • @wagsman9999
    @wagsman9999 3 роки тому

    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.

  • @nicklandreth2527
    @nicklandreth2527 4 роки тому

    I haven't seen all your videos yet. But I am gonna go ahead and give this one the prize for coolest hair prematurely.

  • @mahendrakumarangamuthugane2690
    @mahendrakumarangamuthugane2690 3 роки тому +2

    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.🙏

  • @eyesight2073
    @eyesight2073 2 роки тому +2

    5:23
    Can anybody explain where exactly the 1st instance is created?
    I could only see its intialized with nullptr.

  • @jaibalajt833
    @jaibalajt833 3 роки тому

    He changed my generic definition for singleton class !
    Nice tutorial :P

  • @Gilpow
    @Gilpow 6 років тому +11

    6:50 you forgot to cut lol

  • @prashantgupta6885
    @prashantgupta6885 3 роки тому +4

    6:55 Glitch in the matrix

  • @lucamacchi9129
    @lucamacchi9129 4 роки тому

    Man, you're simply the best

  • @Tristar3SLO
    @Tristar3SLO 6 років тому +1

    Hey, great video. Just one question. Isnt dereferencing a null pointer undefined behavior?

  • @konrad3688
    @konrad3688 7 років тому

    I think you should mention that {} creates a scope. (Or maybe you did that and I missed it). Nice vid, keep going :D

  • @landryplacid4065
    @landryplacid4065 3 роки тому

    ohh!! it was his phone, moved my phone a series of time thinking I was the one causing the interference! :) Nice video

  • @HexagonalClosePacked
    @HexagonalClosePacked 4 роки тому +4

    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.

  • @andreistefanie
    @andreistefanie 7 років тому +9

    I really like how you transitioned into the singleton implementation (this is also how Scott Meyers suggests it)

    • @smolboii1183
      @smolboii1183 5 років тому

      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

    • @cccccroge
      @cccccroge 5 років тому

      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)

  • @hamzamameche3893
    @hamzamameche3893 3 роки тому

    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?

  • @Popart-xh2fd
    @Popart-xh2fd Рік тому

    5:09 but because you set the class instance pointer to nullptr if you run it it will crash, right?

  • @freddo1230
    @freddo1230 5 років тому

    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;

  • @monishkumardurairaj3038
    @monishkumardurairaj3038 4 роки тому

    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?

  • @adamhendry945
    @adamhendry945 3 роки тому

    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)?

  • @p76yu78yu
    @p76yu78yu 5 років тому

    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 ?

  • @deltarambo6230
    @deltarambo6230 4 роки тому

    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.

  • @fahadbutt7599
    @fahadbutt7599 3 роки тому

    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?

  • @exrebok1
    @exrebok1 4 роки тому +1

    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.

  • @BornAgainstAll
    @BornAgainstAll 2 роки тому

    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?

  • @om3rbenbrahim488
    @om3rbenbrahim488 3 роки тому +2

    setting the singleton pointer to null results in an ub (undefined behavior) so we have to pass the instance's address

  • @WayneRiesterer
    @WayneRiesterer 5 років тому +1

    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...

  • @linhnguyentrankhanh1413
    @linhnguyentrankhanh1413 4 роки тому

    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 :))))

  • @Knot2goodAtIt
    @Knot2goodAtIt 3 роки тому

    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?

  • @croncoder862
    @croncoder862 3 роки тому

    if I remove the & from the return type, it starts behaving like an instance method. Why ?

  • @mamertvonn
    @mamertvonn 3 роки тому

    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?

  • @godjacky2
    @godjacky2 5 років тому

    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?

  • @qidex
    @qidex Рік тому

    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. 🤍

  • @PROGAMER-xx4xc
    @PROGAMER-xx4xc 4 роки тому

    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.??

  • @abdelrhmanabdelhmaed5857
    @abdelrhmanabdelhmaed5857 3 роки тому

    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?

  • @jawadch8723
    @jawadch8723 Рік тому

    Amazing!!! 👍

  • @Katatonya
    @Katatonya 3 роки тому

    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?

  • @AbdulMoiz-ho8rx
    @AbdulMoiz-ho8rx 2 роки тому

    Excellent

  • @autumnleaf8483
    @autumnleaf8483 2 роки тому

    Dude just went back in time epic...

    • @autumnleaf8483
      @autumnleaf8483 2 роки тому

      Oh he just forgot to put this before Static video.

  • @CanKarakuzulu
    @CanKarakuzulu 5 років тому +3

    I had to change position of my phone several times before noticing that the static was coming from video.

  • @wesleylim5932
    @wesleylim5932 3 роки тому

    5:00 Can someone tell me why he is able to access s_Instance which is a private class variable?

  • @superpb600
    @superpb600 6 років тому

    Btw usually you declare a private constructor to prevent a developer from creating another instance of the Singleton.

  • @Markgraf_ON
    @Markgraf_ON 3 роки тому

    I didn't know about locale static, but i just guess out and answered at code interview. Well, that just worked lol

  • @wolfsdendogsanctuary731
    @wolfsdendogsanctuary731 5 років тому

    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.

  • @w3w3w3
    @w3w3w3 4 роки тому

    I wish you explained it a bit more like the :: and such... totally just jumped into that lol.

  • @nedolium
    @nedolium Рік тому

    The basic incrementing example with the static value inside the function reminds me a lot of Python generators.

  • @teddy-mryamz
    @teddy-mryamz 7 років тому

    I recently just needed this functionality and wished it were possible however I was using java in LD39.

  • @parthasarathipatra9483
    @parthasarathipatra9483 2 роки тому

    That singleton example was a good brain twister

  • @adrianoldchannel2494
    @adrianoldchannel2494 6 років тому

    Very awesome

  • @harshababsingh4226
    @harshababsingh4226 3 роки тому

    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?

    • @ashutosh2933
      @ashutosh2933 3 роки тому +1

      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.

  • @DominicVictoria
    @DominicVictoria 6 років тому +1

    Can you explain the static at 1:30

  • @usman8872
    @usman8872 Рік тому

    i=0 is there in start of Function, why it is not setting it to 0 every time, when Function is called.

  • @danielkrajnik3817
    @danielkrajnik3817 3 роки тому

    are you using vim keybindings? how did you copy it five times

  • @seymurmammadov3868
    @seymurmammadov3868 3 роки тому

    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()?

    • @al.jibran
      @al.jibran 3 роки тому

      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.

  • @CViniciusSDias
    @CViniciusSDias 3 роки тому

    So does this make memory to be allocated in the heap?

  • @kiyasuihito
    @kiyasuihito 8 місяців тому

    My employer should pay you for teaching me c++. On the job training was pretty lacking unfortunately 😂 but you come in clutch 🎉

    • @virno69420
      @virno69420 5 місяців тому

      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?

  • @57ashdot
    @57ashdot 5 років тому

    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.

  • @OneShot_cest_mieux
    @OneShot_cest_mieux 4 роки тому +1

    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)

    • @OneShot_cest_mieux
      @OneShot_cest_mieux 4 роки тому

      @Peterolen I understand, idk why but it works anyway, maybe an undetermined behavior

  • @zch7491
    @zch7491 4 роки тому

    wouldn't we also need to make the default constructor inaccessible for singleton class?

  • @lucasmorais3694
    @lucasmorais3694 5 років тому +1

    This hair of yours is so damn crazy, I love it xD

  • @lucasp1813
    @lucasp1813 4 роки тому

    Wow!. thank you.

  • @094837261
    @094837261 5 років тому +1

    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.

  • @GreenFlame16
    @GreenFlame16 4 роки тому +1

    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?

    • @coenfuse
      @coenfuse 3 роки тому +1

      Marked as Free

    • @GreenFlame16
      @GreenFlame16 3 роки тому

      @@coenfuse so memory cells each have a marker register that holds the flag?

  • @haykav
    @haykav 6 років тому

    That last Singleton example made the tutorial.

  • @jakobzorz7383
    @jakobzorz7383 5 років тому +1

    static ia good for functions that repeat 100 times a second and make a variable each time static keeps it there

  • @udayyadav3489
    @udayyadav3489 5 років тому

    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

  • @DominicVictoria
    @DominicVictoria 5 років тому

    Is it stored in the heap?

  • @kimjitchu3799
    @kimjitchu3799 4 роки тому

    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 >

  • @devopssimon
    @devopssimon 4 роки тому

    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?