are "smart pointers" actually smart?

Sdílet
Vložit
  • čas přidán 8. 09. 2023
  • Thanks again Yubico for sponsoring this video! Go get a Yubikey at www.yubico.com/store/ RIGHT NOW with my offer code LOWLEVEL5 to get 10% off a Yubikey!
    What's the deal with smart pointers? What problems do they solve? Are they actually smart? In this video, I'll talk about what problems a smart pointer solves, the types of smart pointers in C++, and the pro's and con's of the way they solve certain problems.
    But, should you learn C++? Yes. There are a few caveats though.
    🏫 COURSES 🏫 Learn to code in C at lowlevel.academy
    📰 NEWSLETTER 📰 Sign up for our newsletter at mailchi.mp/lowlevel/the-low-down
    🙌 SUPPORT THE CHANNEL 🙌 Become a Low Level Associate and support the channel at / lowlevellearning
    🛒 GREAT BOOKS FOR THE LOWEST LEVEL🛒
    C Programming Language, 2nd Edition: amzn.to/3OKh3q2
    C++ Crash Course: A Fast-Paced Introduction: amzn.to/3qdZILK
    The Rust Programming Language, 2nd Edition: amzn.to/3MHaS36
    🔥🔥🔥 SOCIALS 🔥🔥🔥
    Low Level Merch!: www.linktr.ee/lowlevellearning
    Follow me on Twitter: / lowleveltweets
    Follow me on Twitch: / lowlevellearning
    Join me on Discord!: / discord
  • Věda a technologie

Komentáře • 276

  • @LowLevelLearning
    @LowLevelLearning  Před 7 měsíci +4

    Thanks again Yubico for sponsoring this video! Go get a Yubikey at www.yubico.com/store/ RIGHT NOW with my offer code LOWLEVEL5 to get 10% off a Yubikey!

  • @allenmelikian7885
    @allenmelikian7885 Před 8 měsíci +372

    "smart pointers" actually more intelligent than 50% of the programmers

    • @IBelieveInCode
      @IBelieveInCode Před 8 měsíci +4

      Not than I.

    • @vishaldas9312
      @vishaldas9312 Před 8 měsíci +4

      In their defense, smart pointers are of all tools available to developers but not everyone can adapt to a certain tool. Actually remapping mental model and using smart pointers everywhere in the codebase may be troublesome especially if working on a large project with multiple people in collaboration.

    • @_framedlife
      @_framedlife Před 8 měsíci +6

      so just "above average pointers"

    • @markojojic6223
      @markojojic6223 Před 8 měsíci +2

      My profesor once said that strings are more complicated than a certain fraction of people present at an undisclosed meeting.

    • @anon-fz2bo
      @anon-fz2bo Před 8 měsíci +2

      1 bjarne == 100 programmers

  • @chie5747
    @chie5747 Před 8 měsíci +297

    According to the CPP Core Guidelines F.7, you should pass raw pointers or references if the function doesn't change the ownership of your variable.
    If you apply this rule, then you can easily distinguish owning smart pointers from non-owning raw pointers.
    Additionally, this makes your function more useful because it will accept a pointer/reference, regardless of how the object has been allocated.

    • @loading_wait
      @loading_wait Před 8 měsíci +14

      You still run into not knowing if deeply nested functions (within a library you didn't write for example) ever try to drop.

    • @etopowertwon
      @etopowertwon Před 8 měsíci

      ​@@loading_wait Most library authors know that pointer can come from new/new[]/pmr/malloc()/stack and therefore it CAN'T be deleted unless they themselves allocated it.
      And by "most" I mean "probably everyone beside authors of the libs that are used by Low Level Learning and loading_wait, definitely everyone in my last 2 decades of using c++ and not hitting this problem even once"
      I had more troubles with implicit intfloat conversion than with not knowing if somebody decided to call delete for no apparent reason.
      This video is bad. Its takes are bad. SeanCline below explained very well how to use.

    • @azmah1999
      @azmah1999 Před 8 měsíci

      If the library you're using is written in modern C++ it should be OK since they should follow the core guidelines. The problems arise when you have to call a C library in that case check the doc. But I guess in general, if your gut tells you this function might do something fishy, check the doc.

    • @StEvUgnIn
      @StEvUgnIn Před 8 měsíci +1

      It’s always best to follow the guidelines

    • @renato360a
      @renato360a Před 7 měsíci +2

      @@loading_wait true but it's fine if you know that's not your case. It also doesn't seem worth it for me to safeguard against the future possibility if it's not expected.

  • @SeanCline
    @SeanCline Před 8 měsíci +208

    The code example at 5:23 hurts to see, but I've definitely seen code like that in the wild before.
    In this case, Dog should be passed by reference avoiding the whole problem of ownership. main() still owns the Dog, but keeps it alive long enough for do_something to complete its work.
    In general, a function does not need to take a unique_ptr or shared_ptr as an argument unless it needs to participate in the argument's lifetime. Only when the function needs to extend the lifetime of a shared_ptr (keeping it from being destroyed), or will take ownership of the unique_ptr (destroying it when it's no longer needed) does a smart pointer need to be passed as an argument.

    • @rockerdudeb
      @rockerdudeb Před 8 měsíci +1

      Really helpful explanation

    • @eloigg6419
      @eloigg6419 Před 8 měsíci +5

      Was looking for this comment. Use references to keep ownership just like in Rust

    • @bakedbeings
      @bakedbeings Před 8 měsíci

      Yeah, Bjarne's a big advocate of references and their reduction of complexity. Don't give admin controls to any function/object that doesn't need it.

    • @RenXZen
      @RenXZen Před 8 měsíci +1

      Totally agree with this explanation. We don't need add complexity when it can be avoided and still get the same result.

    • @right_jehoon
      @right_jehoon Před 8 měsíci +4

      I was curious about why not use pass by reference. This comment explains everything.

  • @someon3
    @someon3 Před 8 měsíci +88

    Shared pointers shouldn't be used like that. They exist to share the ownership, in that case u should have used a raw ptr or simply a reference/const reference. Shared pointers add an extra layer of overhead due to the implementation itself; don't use them to move stuff between functions

    • @Spartan322
      @Spartan322 Před 8 měsíci +4

      While the overhead is there, its usually the most insignificant detail, (unless you're dealing with multi-threading, but the standard smart pointers aren't helpful in any of those cases anyway) but yes using a shared pointer like this is not really correct, usually a shared pointer is for complex scenarios where you can't be sure of when the pointer should be freed because of all the things that depend on a valid value, containers being one of the most useful cases.

  • @etopowertwon
    @etopowertwon Před 8 měsíci +47

    * Pass reference if value can't be null
    * Pass raw non-const pointer if it can be null
    * No, it doesn't defeat the purpose. Don't call delete - leave all memory management to unique_ptr.

    • @Spartan322
      @Spartan322 Před 8 měsíci +3

      There's also span, mdspan, and string_view, so there's even less incentive now to touch raw pointers now for things that smart pointers can't do well. There's also out_ptr and inout_ptr to assist the smart pointers.

    • @Megalcristo2
      @Megalcristo2 Před 6 měsíci +2

      I have a better one:
      Never use raw pointers

    • @Spartan322
      @Spartan322 Před 6 měsíci

      @@Megalcristo2 You still have to use them for non-owning single instances in memory.

    • @Megalcristo2
      @Megalcristo2 Před 6 měsíci

      @@Spartan322 You can use references for that. If by memory you mean the heap, then you better use the "ownership" concept.
      Maybe "never" is a strong word there are some situations where they are still useful, like observer pattern or handling dynamic memory within a static variable (although I would personally still use smart pointers here)

    • @Spartan322
      @Spartan322 Před 6 měsíci

      @@Megalcristo2 Biggest cases and why you can't really use references is when you need to also return an empty pointer and your class doesn't or can't have a tombstone state. (which usually you don't want if your class consumes more then a pointer size of memory on construction anyway)

  • @WouterStudioHD
    @WouterStudioHD Před 8 měsíci +45

    This is REALLY BAD ADVICE! You need to make the function take a Dog& (reference). Shared pointers are a last resort and are often a sign of a bad design!

    • @sinom
      @sinom Před 8 měsíci +7

      Shared ptrs in general aren't bad design. But using them like this definitely is. You basically only want to pass a shared pointer to a function like this if it then saves that shared pointer somewhere (like in a vector) but you still want the original location to also own it
      (Though even in those cases using weak_ptr might be more useful)

    • @WouterStudioHD
      @WouterStudioHD Před 8 měsíci

      @@sinom Nope, shared_ptr in general is a sign of a bad design. It makes lifetimes unclear, which makes it harder to reason about your code. Always avoid shared_ptr and prefer unique_ptr. You should only use it when there is no other option. You often see new C++ programmers slap a shared_ptr on everything, while the seasoned C++ professionals pretty much only use unique_ptr.

    • @nepp9574
      @nepp9574 Před 8 měsíci

      @@sinom​​⁠​⁠​⁠might also add that you can use shared ptrs multiple places but also want to pass it as an argument to a method that does not have the intention of sharing ownership. In that case you would use a const ref shared ptr though. A const raw pointer can also be passed using .get() but will require the whole method to be const, while the const ref shared ptr does not.

  • @LuckieLordie
    @LuckieLordie Před 8 měsíci +65

    You don't need to convert to a shared_ptr here I think. You can take a reference in the function and save the ownership semantics to the passing function.
    The way I had it described to me is that smart pointers are all about ownership, if you pass a shared pointer to a function you can't expect that memory to be free'd when you get rid of the object in your scope(different if you convert to weak and pass that). But you're saying "hey, function, you take equal ownership to this data type. When we're BOTH done with it then it can be released and only then".
    Whereas a unique_ptr passing a reference down the call stack is saying "I retain ownership of this memory, you can use it, but you may not affect its lifetime". You still have to be strict with references like you do with normal pointers, but you can express whether or not you're going to be interested in the lifetime of the underlying object or not by using the function signature.

  • @metal571
    @metal571 Před 8 měsíci +30

    To add to this: see also the C++ Core Guidelines, which lay out ground rules for how to pass and use smart pointers.

    • @hypnoz7871
      @hypnoz7871 Před 8 měsíci

      Heaphone guy metal571 also in low level programming ??
      Damn the world is small :)

    • @metal571
      @metal571 Před 8 měsíci +1

      Yeah this is my full time real job of being a C, C++, and Python senior software engineer

  • @sinom
    @sinom Před 8 měsíci +29

    if you don't want to transfer ownership to a different function then in 99.5% of cases the proper way of doing it is taking the parameter by reference instead of by value or move.

  • @_tsmn_5031
    @_tsmn_5031 Před 8 měsíci +13

    I dont understand why u did all of these things. You could just pass by reference or pass by ptr.

  • @PieCoPresident
    @PieCoPresident Před 8 měsíci +14

    0:30 "sizeof(somepointer)" is almost always a bug as well. You're allocating space (and zeroing the memory) for an object, but you're only requesting enough space for a single pointer, rather than whatever type auth actually points to.

    • @an0nsaiko890
      @an0nsaiko890 Před 8 měsíci +1

      I noticed that too. The correct syntax would be `sizeof(*somepointer);`.

    • @erikkonstas
      @erikkonstas Před 7 měsíci +2

      There's also a huge lack of #includes and declarations there...

  • @osamaaj
    @osamaaj Před 8 měsíci +5

    Code at 0:30 could possibly have more than just one bug. I know it's for demonstration purposes, but I got fixated on malloc and memset that I didn't get to see the use after free part.

    • @erikkonstas
      @erikkonstas Před 7 měsíci +2

      LOL the lack of declarations for auth and service sold it for me, and then the lack of #includes as well...

  • @TS-by9pg
    @TS-by9pg Před 8 měsíci +11

    As a fellow Rustacean this genuinely makes me bad for C++ people. You need so much boilerplate to make a unique pointer and even after all of that the compiler can't catch that it was moved and you still get a segfault

    • @_tsmn_5031
      @_tsmn_5031 Před 8 měsíci +10

      This video makes it seem harder and more error prone. You should check other videos to see that it is not that hard and it is pretty safe if you know what you are doing. I know c/c++ can have memory leak issues but unique_ptr actualy solves most of the problems

    • @MI08SK
      @MI08SK Před 8 měsíci +2

      When a unique pointer is moved it becomes a null pointer( it stops pointing to the original memory but to the address 0x0000). Additionaly 99% of times you wouldn't move a unique_pointer but pass it by reference

    • @jolynele2587
      @jolynele2587 Před 7 měsíci +2

      he is not using the pointers very properly...

  • @Beatsbasteln
    @Beatsbasteln Před 8 měsíci +6

    maybe we should come up with "dumb pointers" then and call them "std::generic_ptr" and "std::greedy_ptr". or we make pointers based on cool films and series that we watched, like "std::clannad_ptr", a pointer that periodically forgets what it pointed to, and the thing it pointed to suffers from traumatic events in the past

    • @Torabshaikh
      @Torabshaikh Před 15 dny +1

      "std::clannad_ptr" makes me want to cry.

  • @tomkimsour
    @tomkimsour Před 2 měsíci

    Thanks ! I encountered this issue at work today and this helped me validating my decisions and my understanding

  • @Uerdue
    @Uerdue Před 8 měsíci +13

    In the first code snippet:
    ```c
    auth = malloc(sizeof(auth));
    ...
    strcpy(auth->name, line + 5);
    ```
    The `malloc` call does not necessarily allocate enough bytes for the `auth` structure, but merely the 8 bytes for a pointer to it. Depending on the size of the `auth` struct (or rather, the offsets of the `name` and `auth` fields within it), things will go wrong here as well.

  • @anon_y_mousse
    @anon_y_mousse Před 8 měsíci +3

    I think the thing you should have gone over more is how encapsulating them in a class like this allows them to be deconstructed automatically when they go out of scope. I find that when I write C++ I tend to not allocate anything myself and instead I just allow the container classes to handle all of that for me. If I need a custom object I can write the allocation in the constructor and deallocation in the destructor and I'm done. Since the standard container classes call my destructors for me, I don't have to care about allocation most of the time. It's only when I write C that I have to care and I've got methods for dealing with it there, but it's never as easy when I have to create some new "class" to do things with. I don't hate the way I have my data structures library laid out, but I don't love it either and I constantly wish I had operator overloading and real classes like in C++. I don't totally hate C++ and its syntax, just *most* of it.

  • @redcrafterlppa303
    @redcrafterlppa303 Před 8 měsíci +1

    I would love to see a video about Arenas. Since they are an allocation strategy that isn't used or talked about often even though it's quite powerful and solves the problem of ownership in a quite unique way.

  • @XDsaccottino
    @XDsaccottino Před 8 měsíci +16

    void do_thing_with_dog(const Dog& dog) { dog->bark(); }
    auto dog = std::make_unique();
    do_thing_with_dog(*dog);
    There is no need to pass the unique_ptr to the function and the same is also true for the shared_ptr. They should be passed as smart pointers to free functions or class members only when you want to express changes in the managed object lifetime.

    • @anon1963
      @anon1963 Před 6 měsíci +2

      is this even correct? Dog is not a pointer now and how do you call -> on it?

    • @qqshutup7175
      @qqshutup7175 Před 6 měsíci +1

      @@anon1963 there is a typo in his comment, *dog* is not a *pointer* but a *reference* ... so you can use *.* to access each member
      void do_thing_with_dog(const Dog& dog) { dog.bark(); }

  • @anon-fz2bo
    @anon-fz2bo Před 8 měsíci

    additionally, the most obvious error with the code was (unless imported by a header file which was not shown in the code) auth & service would be 2 undefined identifiers. i also think that (although i may be wrong) as im unsure of the return type of std::move() u could just define the function to take in a reference to a std::unique_ptr. that is, std::unique_ptr& as apposed to std::unique_ptr

  • @coolbrotherf127
    @coolbrotherf127 Před 8 měsíci +4

    Idk about how everyone else does things, but generally speaking, my methodology is to use raw pointers in small, contained algorithms in the methods for objects so I know exactly how and where the pointers are being used. I'll then use smart pointers in the more dynamic parts of the program with a ton of objects being created, deleted, and manipulated all at the same time, possibly in a multi-threaded environment. That's when the dynamic behavior of the program gets really difficult to check for every possible situation a pointer might miss the deallocation point. It of course is possible to use raw pointers very well in every method to increase performance, but in a non-intentive program, the stability of smart pointers makes them a very useful tool.

    • @elcugo
      @elcugo Před 8 měsíci +1

      If you are not transferring ownership, unique_ptr should have the same performance than raw pointers when optimizations are enabled.

    • @coolbrotherf127
      @coolbrotherf127 Před 8 měsíci

      @@elcugo I guess, but why do things the way way when I could do them my way? 😉

  • @maximkulkin2351
    @maximkulkin2351 Před 8 měsíci +2

    Can you see a bug? *Me seeing tons of bugs there* LOL

  • @JATmatic
    @JATmatic Před 8 měsíci +2

    Pass 'unique_ptr x' into function with: void myfunc(Obj & x); myfync(*x)
    I.e. derefence the unique_ptr and pass by reference.
    All C++ smart pointers have X::get() that just return the plain pointer:
    If the unique_ptr can be nullptr use void myfunc(Obj * x); myfync(x.get()) instead.
    However this partly shifts the burden back to programmer:
    Programmer must now guarantee the Obj memory address does not escape from the myfunc().

  • @ludoviclagouardette7020
    @ludoviclagouardette7020 Před 7 měsíci +1

    I would have actually used a unique_ptr reference in the case you presented for the unique pointer. I also kinda like the "returning the unique pointer back" solution in lots of cases

  • @eshedruf
    @eshedruf Před 8 měsíci

    What window manager do you use?

  • @iThomasF
    @iThomasF Před 8 měsíci

    The big thing that I also thing is missed in the advantage of RAII in C++ and smart pointers being a part of that is the ability to reduce cognitive complexity. You can do things like just return in an error case without having to copy paste cleanup a bunch of places or use a go to. You just don’t have to think about clean up so if an input is wrong or whatever you just return instead of having these deeply nested functions that are so common is C code.

  • @abacaabaca8131
    @abacaabaca8131 Před 3 měsíci

    What is the difference between `std::shared_ptr` and pass by reference `&`.
    From my understanding and also from your word shared pointer is a unique pointer that allows multiple other pointers to point to its data on the heap. i.e many pointers with one data.
    On the other hand pass by reference is a pointer that points to another pointer that hold the data on the heap. If the pointer that owns that data got cleaned up when it goes out of scope the reference & will point to invaild data. And in c++ the compiler will give error if doing incorrectly.

  • @alexeydmitrievich5970
    @alexeydmitrievich5970 Před 8 měsíci +1

    I think for function arguments (in non null situations) references are better

  • @robmorgan1214
    @robmorgan1214 Před 8 měsíci +2

    Raw pointers are essential tools for performance programming. Complexity is just as bad for code as carelessness. Practice using dangerous things so you don't screw up when you need to use them. C and C++ memory management continues to exist for a lot of important reasons.

  • @mikaay4269
    @mikaay4269 Před 8 měsíci +1

    "Bork bork I am segmentation fault, mans best friend!"

  • @st8113
    @st8113 Před 8 měsíci +2

    Shared pointers are great, but you've definitely gotta use them judiciously. They come with overhead, and it's easy to leave one in a place where it will never get cleaned up if you're not careful.

    • @MI08SK
      @MI08SK Před 8 měsíci

      They come with overhead when a shared pointer gets created or destroyed

  • @TheVralapa
    @TheVralapa Před 8 měsíci +1

    If the function isn't intended to own the memory use std::unique_ptr& / std::shared_ptr& / T&. Better performance as well.

  • @earx23
    @earx23 Před 7 měsíci +1

    C++ 's smart pointers are optionally smart. I'm glad I switched to Rust.

  • @chicoern
    @chicoern Před 7 měsíci

    And unique_ptr was designed to have zero overhead when compared with raw pointers, so really worth using it

  • @askoldmodera
    @askoldmodera Před 7 měsíci +1

    I doubt code at 0:45 will even run to the point where it uses dangling pointer, because it allocates auth as size of auth, which is size of pointer, and it's clear from the code that auth is some struct that should be atleast 32 bytes long.

  • @PinakiGupta82Appu
    @PinakiGupta82Appu Před 8 měsíci +2

    True! 👍👍
    People should be more careful while using pointers. It's not a disadvantage. Pointers provide low-level controls, so it's a feature. I'm talking about pure C. A bit of proper attention eliminates the majority of memory-related bugs in C.

    • @elcugo
      @elcugo Před 8 měsíci +5

      Ah yes, the make no mistakes strategy of programming, why nobody thought of this.

    • @robmorgan1214
      @robmorgan1214 Před 8 měsíci +1

      ​@elcugo it's why your operating systems and drivers work.
      Good habits work. However they require discipline and professionalism. Most managers have too much heart to fire the guys who have neither. Once again the fish rots from the head. Engineering is not easy. It is in fact detail oriented and hard. The first real computers were designed programmed and maintained by mechanical engineers and machinists... if they didn't hit their numbers on their lathe then the gun director track solution was wrong and that kamikaze killed you and everyone who screwed up the "program". They were properly motivated and their guns usually didn't miss if the radar was online and working properly. The make no mistakes approach works just fine for real engineers that build serious tech.

    • @elcugo
      @elcugo Před 8 měsíci

      @@robmorgan1214 That's a lot of nonsense. People have been killed by engineering mistakes multiple times, millions of dollars lost for memory bugs. Bridges have fallen, rockets exploded.
      "Real engineers" build tolerances into their processes, because they know mistakes will happen. Important products gets tested by months before they get released.
      You are stupidly and dangerously wrong.

    • @anon1963
      @anon1963 Před 6 měsíci +1

      ​@@robmorgan1214everyone makes mistakes, we're not machines

  • @Little-bird-told-me
    @Little-bird-told-me Před 8 měsíci

    Which distro do you use with i3 ?

  • @venny5417
    @venny5417 Před 8 měsíci +1

    yeah, should've gone with a reference
    also, const-ing methods and parameter types is actually really good practice, self documenting code and whatnot
    in C++ we use the following idiom: void doSomething(const std::string& some_string) to declare some_string as a read-only reference and avoid copying. This is really good practice for performance and readability (yes, const& is very readable after C++ damages your brain sufficiently :)

    • @erikkonstas
      @erikkonstas Před 7 měsíci +1

      Said "really good practice" is *REALLY GOOD PRACTICE* , it can be a reason others cuss you out for! Simply put, people often omit that word willy-nilly, which can cause significant errors if even one user of your code uses it.

  • @sehzadeselim863
    @sehzadeselim863 Před 8 měsíci

    Bro, if you use constexpr new, then forgetting about delete will be a compiler error

  • @Spirrwell
    @Spirrwell Před 8 měsíci +2

    That use after free at the beginning isn't the only issue. There's quite a few issues here from basic pointer arithmetic just being wrong and duplicating strings that are not freed. Not to mention how dangerous it is to deal with C strings this way. The line buffer being 128 bytes is the only thing saving you from bad things happening with your already incorrect pointer arithmetic.

    • @somenameidk5278
      @somenameidk5278 Před 8 měsíci +1

      i noticed auth = malloc(sizeof auth) isntead of sizeof *auth almost immediatly

    • @Uerdue
      @Uerdue Před 8 měsíci

      Plus, the `malloc` call being supplied a `sizeof(some_pointer_variable)` as its `size` parameter, causing it to allocate 8 bytes regardless of how large the `auth` struct actually is...

    • @jlewwis1995
      @jlewwis1995 Před 8 měsíci

      @@Uerdue I mean you could get around that by using the struct type name but maybe in this case the struct name is also auth, the full code isn't given so we can't be sure -_-

    • @Spirrwell
      @Spirrwell Před 8 měsíci

      @@jlewwis1995 I can't think of any way to both typedef a struct and declare a variable of the same name in C. That's just gonna lead to compiler errors. The sizeof usage definitely appears wrong. It probably functions okay because malloc will probably allocate more than the 4 or 8 bytes (pointer size) due to it allocating pages.

  • @halavich9672
    @halavich9672 Před 4 měsíci +1

    Thanks for reminding why I love Rust

  • @fantasypvp
    @fantasypvp Před 7 měsíci +1

    As a rust user my first thought would just be to pass a mutable reference into the function lol, it's so much easier, you don't even need a smart pointer to do that

    • @Phantom-lr6cs
      @Phantom-lr6cs Před 29 dny +1

      men if rust is so damn good what are you doing here ? go and code in it

  • @pshr2447
    @pshr2447 Před 7 měsíci

    The whole point of the unique_ptr is so that it makes memory management easier as compared to raw pointers. So the pointer getting freed after a functional stack gets deleted (as the deconstructor of the unique_ptr is called) is not an inconvenience, but it's instead a feature because unlike traditional pointers in heap that may remain in the memory even after going out of scope, unique_ptr make sure this doesn't happen. But i understand the problem which is what if i want to save it from getting deleted in a function so that I can then use it again after the functional stack is deleted.

  • @xartpant
    @xartpant Před 8 měsíci +1

    Just use 128 bit CPUs and allocate the first 64 bits for boundary checking.

  • @pqsk
    @pqsk Před 8 měsíci +2

    But the do_something_with_the_dog, isn't that pass by value? Or is it by reference? In C you'd have to pass a double ptr for pass by reference in order to dealloc. You can modify the members, but the free would do nothing. I just forget the different rules in c++ so maybe I am wrong. I get the point though, but was curious if I was wrong

    • @sinom
      @sinom Před 8 měsíci +1

      It's usually a pass by copy but unique_ptr can't be copied only moved. That's why std::move is required to pass it, it casts the value into an x value expression (somewhat similar to r value expressions in C but with a few differences), allowing the copy to instead call the move constructor. In general move should only be used when you want to transfer ownership over stuff. In general it's less expensive than a copy but can be more expensive than just using a reference. If in C++ you want to signify something is a reference you can either use pointers like in C (T* param) if you want it to be a nullable reference or use the & symbol instead to say it is a non nullable reference (T& param). Non nullable references can be used without having to dereference the parameters while nullable references (pointers) need to be dereferenced (arrow, *, etc.) (And ofc they should always be null checked in the function since they imply you can pass a nullptr into that function without issues. Pass by reference means it isn't null checked since you can't pass null by reference on accident)

    • @pqsk
      @pqsk Před 8 měsíci +1

      @@sinom but I’m talking about the original function when it’s just a pointer and the last line *delete* is called. It wasn’t compiled or ran so I’m just not sure that would work. Again, totally get the point that the video is getting at, but, like you also explained, it would just send a copy which wouldn’t cause a bug.

    • @qqshutup7175
      @qqshutup7175 Před 6 měsíci

      @@sinom code that uses std::move can be written without it and needs to be refactored
      passing unique_ptr by value and returning the same object in the function is the stupidest thing I've ever seen in my life, this video was biased and showed that the language allows this but it would be solved by passing the object itself as a reference or const reference
      no c++ programmer who knows smart pointers would do what he did

    • @ezekieloruven
      @ezekieloruven Před 4 měsíci

      You can dealloc the memory. You just can't NULL the pointer that the caller has unless you double indirect.

    • @pqsk
      @pqsk Před 4 měsíci

      @@ezekieloruven ah yes. That’s right.

  • @shipweck6253
    @shipweck6253 Před 8 měsíci

    so does this mean that if you plan on passing a unique_ptr to a function, you should just make it shared?

    • @grincha09
      @grincha09 Před 8 měsíci +10

      Just pass a const reference

    • @pxolqopt3597
      @pxolqopt3597 Před 8 měsíci

      Just pass a const T&

    • @sinom
      @sinom Před 8 měsíci +6

      No. This video really isn't doing a lot of stuff correctly. If you want to pass a unique_ptr to a function you need to ask yourself. Do you want that function to then own that unique_ptr or does it not need to own it at all. Ownership is usually only relevant if e.g. you're then gonna add it to a vector, member of some struct etc. if like this you just want to call a function on that object in the unique_ptr then what you actually want to do is pass it by reference instead of value. so instead of using
      function(unique_ptr ptr)
      {
      ptr->do_something();
      }
      you want to do
      function(unique_ptr& ptr)
      {
      ptr->do_something();
      }
      (preferably even const ref if possible)
      No need for shared_ptr for simple stuff like this
      shared_ptr is only necessary when for example you have two different vectors that both need to have objects they share between them

  • @skeleton_craftGaming
    @skeleton_craftGaming Před 8 měsíci

    0:33 yes yes I was... I treat any free/delete preceding the usage of the freed/deleted object as a use after free bug weather or not it is checked for... the correct way to write that is have all of the other if statements return/continue then if I reach the bottom of the function/loop I assume that they wanted a reset ... this also fixed the issue of not handling malformed inputs which is another bug in the code (albeit a non critical 1)... actually depending on what the input is used for and how it is gathered I may not omit reset's if statement and out put an error on malformed input...

    • @skeleton_craftGaming
      @skeleton_craftGaming Před 8 měsíci

      also for the sake of readability everything in that while loop should be in its own function (named something like parseServiceCommandFromInuput [I too suck at function naming it is ligit one of the hardest things in programming]) if I were trying to understand what your app does I don't necessarily care what commands you're parsing for there for it would take less time for me to realize that is what you're doing if you just tell me that is what you're doing... also having common patterns like that in [well named] functions helps with debugging because if you follow the "functions only do one thing. And that one thing is only done in that function" rule that limits the number of places I would have to look for bugs...

  • @mobslicer1529
    @mobslicer1529 Před 8 měsíci

    as i understand things from some other videos and sources, you basically use raw and smart pointers, and there are right situations for all of them.

  • @sigasigasiga
    @sigasigasiga Před 7 měsíci

    0:29 isn't this code totally fine? We free `auth` if the `line` variable is equal to "reset", and dereference it only when the `line` variable is equal to "login". One string variable cannot be equal to both of them at the same time

  • @id120266737
    @id120266737 Před 8 měsíci

    both "==" and "->" we saw in the beginning were dis-gus-ting. thanks for coming to my ted talk.

  • @sleepib
    @sleepib Před 8 měsíci

    Did you think we wouldn't notice the camera getting mirrored?

  • @azaleacolburn
    @azaleacolburn Před 7 měsíci +3

    That just sounds like Rust with extra steps

    • @Phantom-lr6cs
      @Phantom-lr6cs Před 29 dny

      men in c++ smart pointers were there before rust appeared on this earth so what sounds rust ? go and do some research men . this annoying rust you are second one who posted nonsense without doing any kind of research . rust is a shit in and out and it lacks tons of things . it doesn't evne let you do things without using shit impl / struct / trait combined . and without using stupid moronic & ' < > _ and moronic things it has . you are just bunch of web developers who never coded a shit in systems language so go and cry somewhere else : D if you like rust be quit here we are talking about c++ not about crap rust

  • @gracicot42
    @gracicot42 Před 7 měsíci

    Unique pointers are unique owner, not a the only possible pointer to an object. Passing things by reference/pointer should be the default when a function don't need to deal with ownership.

  • @g.a.1404
    @g.a.1404 Před 8 měsíci +8

    Agree with the comments here stating that's not how unique or shared pointers should be used. I additionally found it a bit sad that it was implied that adding const to the speak function is annoying. It is (because c++ gets the defaults wrong) but it is necessary. Const correctness prevents bugs as it allows us to clearly state when a mutable pointer or ref is needed and when it is not.

    • @polarpenguin3
      @polarpenguin3 Před 8 měsíci +3

      This. Const correctness is vastly overlooked

    • @erikkonstas
      @erikkonstas Před 7 měsíci

      It also prevents angry users who get errors out of nowhere (they would expect that a function which doesn't mutate anything would accept their const pointer, but no, the compiler just craps out).

  • @skeleton_craftGaming
    @skeleton_craftGaming Před 8 měsíci

    5:30 that would've been a perfict time to introduce auto return type deduction...

  • @m4tt_314
    @m4tt_314 Před 8 měsíci

    0:40 you can also leak memory with multiple ‹auth› in a row

  • @GoofyTHPS
    @GoofyTHPS Před 8 měsíci

    I feel like examples against raw pointers are a bit synthetic.
    The first example is just bad code, don’t use sequential ifs when you mean to do a choice from multiple options (switch or else if chain).
    The second example is just bad practice as well. Don’t delete an object that you got as a pointer parameter. If you have to use a raw pointer, just let the object die with its scope.
    If you know in advance you’ll need to transfer ownership, then purposefully use a smart pointer.
    No need to bloat up the code just because someone else might be coding dangerously.

  • @student99bg
    @student99bg Před 8 měsíci +1

    Why don't we just have our function accept a reference and then we pass *dog, where dog is a unique pointer?

  • @kayakMike1000
    @kayakMike1000 Před 8 měsíci

    Elegant solutions or syntax sugar?

  • @kuhluhOG
    @kuhluhOG Před 8 měsíci

    1:56 besides the fact that you don't actually deallocate the dog, but then again, when the program exists the OS does it for you anyway

  • @bigutubefan2738
    @bigutubefan2738 Před 4 měsíci

    If a function is statically typed to Dog (or any sort of pointer to it), then it might as well be a method of Dog. That's besides the point though - your examples still make perfect sense for generic functions or functions typed to interfaces, without being cluttered.
    Inicidentally I was preparing myself to rant about Yubico yesterday, but I was pleasantly surprised by how easy it was to uninstall their "code container". To their credit, they did that right.

  • @harshkumarmoroliya5272
    @harshkumarmoroliya5272 Před 7 měsíci

    is this similar to rust's Box and Rc but in C++ ?

    • @meanmole3212
      @meanmole3212 Před 7 měsíci

      Yes but you cannot mutate data owned by the Rc references if ownership of the data is shared across multiple different Rc references.

  • @volodymyrchelnokov8175
    @volodymyrchelnokov8175 Před 21 dnem

    To add to the fun, 'this' in class methods is a raw pointer, so both speak and setName could "delete this;".

  • @MatheusAugustoGames
    @MatheusAugustoGames Před 7 měsíci

    Why not use a const unique_ptr&?

  • @curlyfryactual
    @curlyfryactual Před 7 měsíci

    3:35 so passing a raw Dog pointer is risky?

  • @jenselstner5527
    @jenselstner5527 Před 8 měsíci

    Using plain C, that's why I prefer to create my pointers at the very start of a function and destroy them at the very end. I just use a "goto" to the appropriate end from the middle of that function to be sure to leave it after destroying those pointers.

    • @erikkonstas
      @erikkonstas Před 7 měsíci +1

      Yeah, I do that too, sadly there are a lot of people who would shun you off for even thinking about the word "g0t0"...

    • @anon1963
      @anon1963 Před 6 měsíci

      In C it's fine. however, you have better tools than spamming goto's in C++

    • @erikkonstas
      @erikkonstas Před 6 měsíci

      @@anon1963 Wouldn't be so sure of that, with heap-allocated things ("new ...") you'd still need matching deallocations ("delete ..." or "delete[] ...").

    • @anon1963
      @anon1963 Před 6 měsíci

      @@erikkonstas smart pointers do just fine

  • @MrOtaviolucas100
    @MrOtaviolucas100 Před 4 měsíci

    In the first example, "auth" is only freed if the first five characters of "line" are "reset". "auth" will be used again only if the first five characters of "line" are "login". Aside from the bug of using "sizeof(auth)" instead of "sizeof(*auth)" in the malloc and the subsequent memset, there is no problem with use after free.

  • @erikkonstas
    @erikkonstas Před 7 měsíci

    0:27 The bigger bug I see is that #includes for , and , and declarations for auth and service are missing, so the code wouldn't even compile to have a bug...
    1:58 One would never try to do that in C; if you have ownership of the pointer, you must either pass it on or destroy it; if you don't, you do not kill it under any circumstances. Simple as that.

  • @ezekieloruven
    @ezekieloruven Před 4 měsíci

    You also didn't initialize auth or service in the first loop iteration.

  • @polarpenguin3
    @polarpenguin3 Před 8 měsíci

    If you learn anything from this video its that you shouldn't randomly delete pointers you don't own.

  • @TurtleKwitty
    @TurtleKwitty Před 7 měsíci

    The function should have taken a reference, possibly a weak_ptr if it needed to keep a long standing reference but it definitely shouldnt be taking a full on shared_ptr since it should NEVER take ownership proper just look into the pointer

  • @monadstack
    @monadstack Před 8 měsíci

    Bro, this should be intro for Rust

    • @Phantom-lr6cs
      @Phantom-lr6cs Před 29 dny

      lolz kids : D why are you bunch of rust clowns here doing ? go and code in that crap : D
      you think this is exists in c++ cause of rust shit ? in c++ smart pointers were there before rust shit appeared : D go and cry for your rust no one cares :D cuz its dumb and shit syntax and crap langauge where you need 15 mb for just hello world and compilation takes forever : D

  • @1____-____1
    @1____-____1 Před 8 měsíci +3

    Lol, and people say Rust is "hard"...

    • @Phantom-lr6cs
      @Phantom-lr6cs Před 29 dny

      in c++ i can do anything without using smart pointers ever .
      just using functions are enough to create anything . but can you do that in rust ? nope you need bunch of shitty stuff like & ' < > _ . without them you can do zilch nothing yet you have problems with c++ which lets you use whatever the heck do you want ? unlike clown rust ? who doesnt' even let you to have struct constructors inside of the struct itself ? yet lets you to use shitty garbage impl / struct / trait altogether ? LOLZ . yeah seems very sane for me : D shitty syntax like haskell : D every language i ever used has much better syntax than rust shitty . rust needs some syntax bettering cause its too shitty . rust needs rust++ with many more things and it could be used but now ? shitty in and out and garbage LOLZ . they have amde haskell like programming language and want us to use that shitty thing : D no thank you and you can have and use rust shit for everything you wish and want and no one gives a damn : D

  • @wijiler5834
    @wijiler5834 Před 8 měsíci +1

    Pointer moment

  • @cherubin7th
    @cherubin7th Před 8 měsíci +1

    Wow this is like the nightmare version of Rust and still segfaults if you don't do all that voodoo.

  • @RuRu-vm6yw
    @RuRu-vm6yw Před 7 měsíci

    Do you only teach C in the “academy”?
    Interested in more advanced topics in C++, not so much in C.
    Let me know if you got something to suggest :D

  • @janisir4529
    @janisir4529 Před 4 měsíci

    You should almost never directly call new or delete if you use smart pointers.
    With that rule passing in a raw pointer is fine if you want to do a null check, but that function should have taken a Dog reference.
    Using shared pointer is a horrible idea unless you actually need the functionality it provides. The performance overhead of reference counting is huge.
    Passing smart pointers between functions should be only done as a sign of explicit ownership transfer.

  • @nevokrien95
    @nevokrien95 Před 8 měsíci

    Why didn't u use a weak pointer for that function situation? Its what they r made to do.
    It's less overhead and more clear who owns what

  • @dickheadrecs
    @dickheadrecs Před 8 měsíci

    they manage memory for you. not RAM, but your own memory that forgets to deallocate

  • @user-uj4gr9ql4m
    @user-uj4gr9ql4m Před 7 měsíci

    0:33
    you know, to call something "vulnerability" you need to make sure it really is something serious and not just a clear sign of 1iq brain

  • @kirdow
    @kirdow Před 21 dnem

    not me waiting for LLL to do this:
    void do_something_with_the_dog(const std::unique_ptr& d) {
    d->setName("asdfasdf");
    d->speak();
    }
    std::unique_ptr ralf = std::make_unique();
    do_something_with_the_dog(ralf);
    Basically, take in a const reference to the unique_ptr, that way you don't copy it, but can still use it exactly as if you did. This is usually what you'd do when handling unique_ptr to other functions.

  • @danielvalle8875
    @danielvalle8875 Před 8 měsíci

    Good choice of sponsor

  • @js46644
    @js46644 Před 8 měsíci

    I told my vet that I moved my dog and he got deleted and they looked at me kinda funny.

  • @claverbarreto5588
    @claverbarreto5588 Před 8 měsíci

    Me* Fellas: hey fellas, remember those traumas inducing scary C/C++ pointers thingy?
    Fellas* Me: Are they dead yet?
    Me* Fellas: No, they're smarter now💀💀💀

  • @TheRealMangoDev
    @TheRealMangoDev Před 7 měsíci

    should you use std::shared_ptr() or std::make_shared() btw. I dont think theres actually a difference, but still...

  • @dickheadrecs
    @dickheadrecs Před 2 měsíci

    modern c++27 smart pointers are weak_ptr, mid_ptr and chad_ptr

  • @yihan4835
    @yihan4835 Před 8 měsíci

    Bad example. Should have just passed Dog as a reference like Dog & d or const Dog & d. A function that operate on an object should not care about if it is a pointer or not. When you call the func, just dereference it.
    Also should not pass shared pointer to a function like that, the function does not own anything. Doing this also incur unnecessary performance overhead from the atomic reference counting. Okay if you do it less frequently, but I would never do this in any function that will be called hundreds of times or more.

  • @MrFunny01
    @MrFunny01 Před 8 měsíci

    Use after free becomes use after move smh

  • @01rnr01
    @01rnr01 Před 8 měsíci

    How do you check if a pointer is freed? ;)

    • @ohwow2074
      @ohwow2074 Před 7 měsíci

      There are a few OS specific ways of doing it on Linux systems. You can definitely try one of those and see if your pointer is valid or not. But there's no standard way of doing it. So just write healthy code.

    • @01rnr01
      @01rnr01 Před 7 měsíci

      @@ohwow2074 Can you share a few of these? (the question is generally to the author so mentions its a good idea to check if the pointer is null *or freed/valid*)

    • @ohwow2074
      @ohwow2074 Před 7 měsíci

      @@01rnr01 here is a video:
      czcams.com/video/xCxI2GIFdZo/video.htmlsi=uYFd8mtbsOvweVgm
      And no. It's actually a bad and harmful idea to check pointers at runtime especially in release builds. The only exception to this is that you can and should always check for null pointers to make sure things are ok. That's good practice.

    • @01rnr01
      @01rnr01 Před 7 měsíci

      @@ohwow2074 That’s why I pointed it out in the first place ;)

    • @01rnr01
      @01rnr01 Před 7 měsíci

      not to mention any os level mechanism cannot accommodate for any kind of pool allocators, caching etc

  • @foxiuc1337
    @foxiuc1337 Před 8 měsíci

    Or just use const right

  • @wilcekmay9052
    @wilcekmay9052 Před 8 měsíci

    But why doing soemething like you did:
    do_something_with_the_dog(ralf);
    instead just this:
    ralf->do_something_with_the_dog();
    ???
    You could remain unique_ptr and still have void and not need to pass dog to the dog's class

  • @Christian-of1tz
    @Christian-of1tz Před měsícem

    I did not work with Rust but hearing about unique_ptr sounds a lot like the ownership model of Rust. But you don't seem to like it?

  • @fredrikhagman2724
    @fredrikhagman2724 Před 2 měsíci

    You should make this video again after you read up on the subject.

  • @paivacn08
    @paivacn08 Před 7 měsíci

    There is another "smart pointer" not mentioned... weak_ptr... But it is so complicated...

  • @torphedo6286
    @torphedo6286 Před 8 měsíci

    I hate the behaviour of adding values to pointers in C... why does adding one add the size of the pointer's data type? I hate having to cast to uintptr_t every time I do pointer math.

    • @erikkonstas
      @erikkonstas Před 7 měsíci

      Because that's way more logical than what you want... also, if you really want to misalign the pointer, you should be casting to (char *) (or its signed or unsigned variants) instead of (uintptr_t); the latter is for getting the address out of a pointer.

  • @philipstoop1955
    @philipstoop1955 Před 8 měsíci +1

    Poor mans borrow checker

    • @Phantom-lr6cs
      @Phantom-lr6cs Před 29 dny

      dumb web developers rust XD
      more likely web devs who don't have enough brain to use memory allocation and look carefully what they code : D

  • @bluesillybeard
    @bluesillybeard Před 8 měsíci +14

    I still prefer Rust's way of memory safety, but this is definitely useful for when I'm inevitably snooping around c++ code.

    • @seabrookmx
      @seabrookmx Před 8 měsíci +17

      Unique pointers _are_ Rust's way (ownership and borrow semantics) but C++ just defaults to being unsafe for compatibility.
      Likewise, shared pointers are the same as using Rc in Rust.
      I definitely prefer the Rust syntax though it's way less verbose!

    • @climatechangedoesntbargain9140
      @climatechangedoesntbargain9140 Před 8 měsíci

      Rusts way includes compiler errors on such mistakes@@seabrookmx

    • @meanmole3212
      @meanmole3212 Před 7 měsíci

      @@seabrookmx The "Rust's way" happens at compile time without overhead during runtime unlike with C++ if you use smart pointers whose references will be counter during runtime. If you opt for speed by not using smart pointers with C++, you'll pay for it in terms of potential runtime crashes. If you explicitly use Rc in Rust, then you are on the same line with C++'s smart pointers in terms of speed. In Rust you still pay for the complexity of dealing with the borrow checker, which may or may not be a problem dependening on the developer.

  • @islandcave8738
    @islandcave8738 Před měsícem

    Or you just always set unallocated pointers to null and always check for null before using and set to null after freeing it. Also be careful when reassigning it not to leave dangling unused memory.

  • @NithinJune
    @NithinJune Před 2 měsíci

    this video and these comments have only confused me more 😭