are "smart pointers" actually smart?

  Переглядів 67,502

Low Level Learning

Low Level Learning

8 місяців тому

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

КОМЕНТАРІ: 276
@LowLevelLearning
@LowLevelLearning 7 місяців тому
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 8 місяців тому
"smart pointers" actually more intelligent than 50% of the programmers
@IBelieveInCode
@IBelieveInCode 8 місяців тому
Not than I.
@vishaldas9312
@vishaldas9312 8 місяців тому
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 8 місяців тому
so just "above average pointers"
@markojojic6223
@markojojic6223 8 місяців тому
My profesor once said that strings are more complicated than a certain fraction of people present at an undisclosed meeting.
@anon-fz2bo
@anon-fz2bo 8 місяців тому
1 bjarne == 100 programmers
@chie5747
@chie5747 8 місяців тому
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 8 місяців тому
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 8 місяців тому
​@@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 8 місяців тому
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 7 місяців тому
It’s always best to follow the guidelines
@renato360a
@renato360a 7 місяців тому
@@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 8 місяців тому
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 8 місяців тому
Really helpful explanation
@eloigg6419
@eloigg6419 8 місяців тому
Was looking for this comment. Use references to keep ownership just like in Rust
@bakedbeings
@bakedbeings 8 місяців тому
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 8 місяців тому
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 8 місяців тому
I was curious about why not use pass by reference. This comment explains everything.
@someon3
@someon3 8 місяців тому
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 8 місяців тому
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 8 місяців тому
* 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 8 місяців тому
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 6 місяців тому
I have a better one: Never use raw pointers
@Spartan322
@Spartan322 6 місяців тому
@@Megalcristo2 You still have to use them for non-owning single instances in memory.
@Megalcristo2
@Megalcristo2 6 місяців тому
@@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 6 місяців тому
@@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)
@LuckieLordie
@LuckieLordie 8 місяців тому
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 8 місяців тому
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 8 місяців тому
Heaphone guy metal571 also in low level programming ?? Damn the world is small :)
@metal571
@metal571 8 місяців тому
Yeah this is my full time real job of being a C, C++, and Python senior software engineer
@WouterStudioHD
@WouterStudioHD 8 місяців тому
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 8 місяців тому
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 8 місяців тому
@@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 8 місяців тому
@@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.
@sinom
@sinom 8 місяців тому
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 8 місяців тому
I dont understand why u did all of these things. You could just pass by reference or pass by ptr.
@PieCoPresident
@PieCoPresident 8 місяців тому
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 8 місяців тому
I noticed that too. The correct syntax would be `sizeof(*somepointer);`.
@erikkonstas
@erikkonstas 7 місяців тому
There's also a huge lack of #includes and declarations there...
@XDsaccottino
@XDsaccottino 8 місяців тому
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 6 місяців тому
is this even correct? Dog is not a pointer now and how do you call -> on it?
@qqshutup7175
@qqshutup7175 6 місяців тому
@@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(); }
@osamaaj
@osamaaj 8 місяців тому
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 7 місяців тому
LOL the lack of declarations for auth and service sold it for me, and then the lack of #includes as well...
@tomkimsour
@tomkimsour 2 місяці тому
Thanks ! I encountered this issue at work today and this helped me validating my decisions and my understanding
@JATmatic
@JATmatic 8 місяців тому
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().
@Uerdue
@Uerdue 8 місяців тому
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 8 місяців тому
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.
@anon-fz2bo
@anon-fz2bo 8 місяців тому
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
@TS-by9pg
@TS-by9pg 8 місяців тому
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 8 місяців тому
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 8 місяців тому
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 7 місяців тому
he is not using the pointers very properly...
@redcrafterlppa303
@redcrafterlppa303 8 місяців тому
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.
@abacaabaca8131
@abacaabaca8131 3 місяці тому
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.
@Beatsbasteln
@Beatsbasteln 8 місяців тому
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 14 днів тому
"std::clannad_ptr" makes me want to cry.
@coolbrotherf127
@coolbrotherf127 8 місяців тому
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 8 місяців тому
If you are not transferring ownership, unique_ptr should have the same performance than raw pointers when optimizations are enabled.
@coolbrotherf127
@coolbrotherf127 8 місяців тому
@@elcugo I guess, but why do things the way way when I could do them my way? 😉
@ludoviclagouardette7020
@ludoviclagouardette7020 7 місяців тому
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 8 місяців тому
What window manager do you use?
@iThomasF
@iThomasF 8 місяців тому
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.
@robmorgan1214
@robmorgan1214 8 місяців тому
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.
@maximkulkin2351
@maximkulkin2351 8 місяців тому
Can you see a bug? *Me seeing tons of bugs there* LOL
@TheVralapa
@TheVralapa 8 місяців тому
If the function isn't intended to own the memory use std::unique_ptr& / std::shared_ptr& / T&. Better performance as well.
@sehzadeselim863
@sehzadeselim863 8 місяців тому
Bro, if you use constexpr new, then forgetting about delete will be a compiler error
@alexeydmitrievich5970
@alexeydmitrievich5970 8 місяців тому
I think for function arguments (in non null situations) references are better
@pqsk
@pqsk 8 місяців тому
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 8 місяців тому
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 8 місяців тому
@@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 6 місяців тому
@@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 4 місяці тому
You can dealloc the memory. You just can't NULL the pointer that the caller has unless you double indirect.
@pqsk
@pqsk 4 місяці тому
@@ezekieloruven ah yes. That’s right.
@Little-bird-told-me
@Little-bird-told-me 8 місяців тому
Which distro do you use with i3 ?
@shipweck6253
@shipweck6253 8 місяців тому
so does this mean that if you plan on passing a unique_ptr to a function, you should just make it shared?
@grincha09
@grincha09 8 місяців тому
Just pass a const reference
@pxolqopt3597
@pxolqopt3597 8 місяців тому
Just pass a const T&
@sinom
@sinom 8 місяців тому
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
@sigasigasiga
@sigasigasiga 7 місяців тому
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
@st8113
@st8113 8 місяців тому
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 8 місяців тому
They come with overhead when a shared pointer gets created or destroyed
@PinakiGupta82Appu
@PinakiGupta82Appu 8 місяців тому
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 8 місяців тому
Ah yes, the make no mistakes strategy of programming, why nobody thought of this.
@robmorgan1214
@robmorgan1214 8 місяців тому
​@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 8 місяців тому
@@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 6 місяців тому
​@@robmorgan1214everyone makes mistakes, we're not machines
@Spirrwell
@Spirrwell 8 місяців тому
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 8 місяців тому
i noticed auth = malloc(sizeof auth) isntead of sizeof *auth almost immediatly
@Uerdue
@Uerdue 8 місяців тому
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 8 місяців тому
@@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 8 місяців тому
@@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.
@venny5417
@venny5417 8 місяців тому
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 7 місяців тому
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.
@chicoern
@chicoern 7 місяців тому
And unique_ptr was designed to have zero overhead when compared with raw pointers, so really worth using it
@pshr2447
@pshr2447 7 місяців тому
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.
@earx23
@earx23 7 місяців тому
C++ 's smart pointers are optionally smart. I'm glad I switched to Rust.
@skeleton_craftGaming
@skeleton_craftGaming 8 місяців тому
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 8 місяців тому
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...
@kayakMike1000
@kayakMike1000 8 місяців тому
Elegant solutions or syntax sugar?
@fantasypvp
@fantasypvp 7 місяців тому
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 28 днів тому
men if rust is so damn good what are you doing here ? go and code in it
@mikaay4269
@mikaay4269 8 місяців тому
"Bork bork I am segmentation fault, mans best friend!"
@halavich9672
@halavich9672 4 місяці тому
Thanks for reminding why I love Rust
@harshkumarmoroliya5272
@harshkumarmoroliya5272 7 місяців тому
is this similar to rust's Box and Rc but in C++ ?
@meanmole3212
@meanmole3212 7 місяців тому
Yes but you cannot mutate data owned by the Rc references if ownership of the data is shared across multiple different Rc references.
@askoldmodera
@askoldmodera 7 місяців тому
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.
@xartpant
@xartpant 8 місяців тому
Just use 128 bit CPUs and allocate the first 64 bits for boundary checking.
@id120266737
@id120266737 8 місяців тому
both "==" and "->" we saw in the beginning were dis-gus-ting. thanks for coming to my ted talk.
@mobslicer1529
@mobslicer1529 8 місяців тому
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.
@MatheusAugustoGames
@MatheusAugustoGames 7 місяців тому
Why not use a const unique_ptr&?
@curlyfryactual
@curlyfryactual 7 місяців тому
3:35 so passing a raw Dog pointer is risky?
@GoofyTHPS
@GoofyTHPS 8 місяців тому
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.
@skeleton_craftGaming
@skeleton_craftGaming 8 місяців тому
5:30 that would've been a perfict time to introduce auto return type deduction...
@gracicot42
@gracicot42 7 місяців тому
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.
@kuhluhOG
@kuhluhOG 8 місяців тому
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
@m4tt_314
@m4tt_314 8 місяців тому
0:40 you can also leak memory with multiple ‹auth› in a row
@sleepib
@sleepib 8 місяців тому
Did you think we wouldn't notice the camera getting mirrored?
@bigutubefan2738
@bigutubefan2738 4 місяці тому
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.
@student99bg
@student99bg 8 місяців тому
Why don't we just have our function accept a reference and then we pass *dog, where dog is a unique pointer?
@polarpenguin3
@polarpenguin3 8 місяців тому
If you learn anything from this video its that you shouldn't randomly delete pointers you don't own.
@azaleacolburn
@azaleacolburn 7 місяців тому
That just sounds like Rust with extra steps
@Phantom-lr6cs
@Phantom-lr6cs 28 днів тому
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
@TheRealMangoDev
@TheRealMangoDev 7 місяців тому
should you use std::shared_ptr() or std::make_shared() btw. I dont think theres actually a difference, but still...
@TurtleKwitty
@TurtleKwitty 7 місяців тому
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 8 місяців тому
Bro, this should be intro for Rust
@Phantom-lr6cs
@Phantom-lr6cs 28 днів тому
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
@volodymyrchelnokov8175
@volodymyrchelnokov8175 20 днів тому
To add to the fun, 'this' in class methods is a raw pointer, so both speak and setName could "delete this;".
@Christian-of1tz
@Christian-of1tz Місяць тому
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?
@wilcekmay9052
@wilcekmay9052 8 місяців тому
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
@nevokrien95
@nevokrien95 8 місяців тому
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
@g.a.1404
@g.a.1404 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 8 місяців тому
This. Const correctness is vastly overlooked
@erikkonstas
@erikkonstas 7 місяців тому
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).
@erikkonstas
@erikkonstas 7 місяців тому
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.
@wijiler5834
@wijiler5834 8 місяців тому
Pointer moment
@janisir4529
@janisir4529 4 місяці тому
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.
@salytmacska4501
@salytmacska4501 8 місяців тому
Rust developers: "Look what they need just to mimic a fraction of our power."
@mariansalam
@mariansalam 8 місяців тому
unique_ptr came to the c++ STL before rust was even introduced. And may I ask, what do you think is so burdensome about it? Having to type 7 extra characters (as opposed to Box)? Otherwise the functionality is identical, readily available in the standard library, and even with extra features (that might not be present in rust or are behind its unsafe firewall). Regarding your ‘mimicking’, I think you might have gotten it the other way around.
@salytmacska4501
@salytmacska4501 8 місяців тому
@@mariansalam @mariansalam The quote's a meme, don't take it too literally. Though if you want to know why I personally prefer rust's approach, it is because it also gives compile-time checks for ownerships errors. This catches things like what is seen in the video at 4:30
@meanmole3212
@meanmole3212 7 місяців тому
​@@mariansalam Rust does not let you move the ownership of data or unique smart pointer inside a function while allowing usage of that data after the function has been called without compiler errors. That is the power C++ can only dream of, not the extra characters you don't need to type.
@jenselstner5527
@jenselstner5527 8 місяців тому
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 7 місяців тому
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 6 місяців тому
In C it's fine. however, you have better tools than spamming goto's in C++
@erikkonstas
@erikkonstas 6 місяців тому
@@anon1963 Wouldn't be so sure of that, with heap-allocated things ("new ...") you'd still need matching deallocations ("delete ..." or "delete[] ...").
@anon1963
@anon1963 6 місяців тому
@@erikkonstas smart pointers do just fine
@torphedo6286
@torphedo6286 8 місяців тому
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 7 місяців тому
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.
@01rnr01
@01rnr01 8 місяців тому
How do you check if a pointer is freed? ;)
@ohwow2074
@ohwow2074 7 місяців тому
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 7 місяців тому
@@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 7 місяців тому
@@01rnr01 here is a video: ukposts.info/have/v-deo/sHOpfWh-gHyVu6M.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 7 місяців тому
@@ohwow2074 That’s why I pointed it out in the first place ;)
@01rnr01
@01rnr01 7 місяців тому
not to mention any os level mechanism cannot accommodate for any kind of pool allocators, caching etc
@ezekieloruven
@ezekieloruven 4 місяці тому
You also didn't initialize auth or service in the first loop iteration.
@MrOtaviolucas100
@MrOtaviolucas100 4 місяці тому
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.
@cherubin7th
@cherubin7th 8 місяців тому
Wow this is like the nightmare version of Rust and still segfaults if you don't do all that voodoo.
@user-uj4gr9ql4m
@user-uj4gr9ql4m 7 місяців тому
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
@dickheadrecs
@dickheadrecs 8 місяців тому
they manage memory for you. not RAM, but your own memory that forgets to deallocate
@1____-____1
@1____-____1 8 місяців тому
Lol, and people say Rust is "hard"...
@Phantom-lr6cs
@Phantom-lr6cs 28 днів тому
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
@yihan4835
@yihan4835 8 місяців тому
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.
@kirdow
@kirdow 20 днів тому
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.
@foxiuc1337
@foxiuc1337 8 місяців тому
Or just use const right
@MrFunny01
@MrFunny01 8 місяців тому
Use after free becomes use after move smh
@danielvalle8875
@danielvalle8875 8 місяців тому
Good choice of sponsor
@js46644
@js46644 8 місяців тому
I told my vet that I moved my dog and he got deleted and they looked at me kinda funny.
@raptoress6131
@raptoress6131 7 місяців тому
5:30 💀
@dickheadrecs
@dickheadrecs 2 місяці тому
modern c++27 smart pointers are weak_ptr, mid_ptr and chad_ptr
@claverbarreto5588
@claverbarreto5588 8 місяців тому
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💀💀💀
@PhonyBread
@PhonyBread 8 місяців тому
Guy kinda missed the point... Feels like you're using paradigm/style from other languages, not very C++-onic (or whatever the C++ version of Pythonic is).
@miguelgarciaroman7040
@miguelgarciaroman7040 Місяць тому
But fast as fuck in comparison with python xd, isn’t that the point?
@aniksamiurrahman6365
@aniksamiurrahman6365 3 місяці тому
Call me dumb, bt I fell like practicing some good pointer habits is much better than using smrt pointer. Such complex syntax alone can cause serious bug. After all, you gotto manually check and ensure more stuff with smart pointer than regular raw pointer.
@RuRu-vm6yw
@RuRu-vm6yw 7 місяців тому
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
@bluesillybeard
@bluesillybeard 8 місяців тому
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 8 місяців тому
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 8 місяців тому
Rusts way includes compiler errors on such mistakes@@seabrookmx
@meanmole3212
@meanmole3212 7 місяців тому
@@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 Місяць тому
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.
why are switch statements so HECKIN fast?
11:03
Low Level Learning
Переглядів 357 тис.
why do header files even exist?
10:53
Low Level Learning
Переглядів 336 тис.
Why i think C++ is better than rust
32:48
ThePrimeTime
Переглядів 259 тис.
unlock the lowest levels of coding
7:05
Low Level Learning
Переглядів 214 тис.
Every CSS Animation property
9:26
chunkydotdev
Переглядів 44 тис.
the truth about ChatGPT generated code
10:35
Low Level Learning
Переглядів 202 тис.
everyone should test their code this way
8:34
Low Level Learning
Переглядів 76 тис.
Refs, Scopes and Smart Pointers | Game Engine series
24:55
The Cherno
Переглядів 34 тис.
everything is open source if you can reverse engineer (try it RIGHT NOW!)
13:56
Low Level Learning
Переглядів 1,2 млн
how Google writes gorgeous C++
7:40
Low Level Learning
Переглядів 728 тис.
All Rust string types explained
22:13
Let's Get Rusty
Переглядів 142 тис.
CONCURRENCY IS AN ILLUSION?
16:59
Core Dumped
Переглядів 71 тис.
Xiaomi Note 13 Pro по безумной цене в России
0:43
Простые Технологии
Переглядів 407 тис.
Он Отказался от БЕСПЛАТНОЙ видеокарты
0:40
ЖЕЛЕЗНЫЙ КОРОЛЬ
Переглядів 1,6 млн
🤯Самая КРУТАЯ Функция #shorts
0:58
YOLODROID
Переглядів 3,3 млн
🤯Самая КРУТАЯ Функция #shorts
0:58
YOLODROID
Переглядів 3,3 млн
Apple Event - May 7
38:22
Apple
Переглядів 6 млн