this post was submitted on 08 Jun 2024
1068 points (98.5% liked)

Programmer Humor

19572 readers
1354 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 1 year ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 80 points 5 months ago (43 children)

This graph cuts off early. Once you learn that pointers are a trap for noobs that you should avoid outside really specific circumstances the line crosses zero and goes back into normal land.

[–] [email protected] 16 points 5 months ago (15 children)

I've been using C++ almost daily for the past 7 years and I haven't found a use for shared_ptr, unique_ptr, etc. At what point does one stop being a noob?

[–] [email protected] 3 points 5 months ago (1 children)

Shared poibters are used while multithreading, imagine that you have a process controller that starts and manages several threads which then run their own processes.

Some workflows might demand that an object is instantiated from the controller and then shared with one or several processes, or one of the processes might create the object and then send it back via callback, which then might get sent to several other processes.

If you do this with a race pointer, you might end in in a race condition of when to free that pointer and you will end up creating some sort of controller or wrapper around the pointer to manage which process is us8ng the object and when is time to free it. That's a shared pointer, they made the wrapper for you. It manages an internal counter for every instance of the pointer and when that instance goes out of scope the counter goes down, when it reaches zero it gets deleted.

A unique pointer is for when, for whatever reason, you want processes to have exclusive access to the object. You might be interested in having the security that only a single process is interacting with the object because it doesn't process well being manipulated from several processes at once. With a raw pointer you would need to code a wrapper that ensures ownership of the pointer and ways to transfer it so that you know which process has access to it at every moment.

In the example project I mentioned we used both shared and unique pointers, and that was in the first year of the job where I worked with c++. How was your job for you not to see the point of smart pointers after 7 years? All single threaded programs? Maybe you use some framework that makes the abstractions for you like Qt?

I hope these examples and explanations helped you see valid use cases.

[–] [email protected] 1 points 5 months ago

When you bring threads into it, these exotic features make more sense. I have been doing single-threaded stuff for the most part.

load more comments (13 replies)
load more comments (40 replies)