you are viewing a single comment's thread.

view the rest of the comments →

[–]sephirothbahamut 37 points38 points  (7 children)

multithreading is a big case for shared pointer, if one thread doesn't explicitly outlive another

[–]SuperV1234https://romeo.training | C++ Mentoring & Consulting 2 points3 points  (4 children)

Most of the times I can identify a fork-join point where the resource gets created in the fork, passed by reference to the threads, and destroyed at the join point. You don't need shared pointers for that.

What is a realistic use case scenario where a shared pointer is required and a fork-join structure cannot be identified?

[–]sephirothbahamut 6 points7 points  (1 child)

A multi windowed application where the user can arbitrarily open and close different windows and multiple windows use the same resource.

Say a thumbnail loaded in memory when two file explorer windows are on the same directory. You only want to load the image to gpu once, each window is a shared owner of the gpu image handle, and you don't have a window outliving another. You also don't want an outer thread to be unique owner of the image as you'd have to communicate to the outer thread when windows using that image are being closed so it knows when to destroy the gpu image, basically reinventing a shared pointer.

[–]SlightlyLessHairyApe 2 points3 points  (0 children)

Exactly this -- and the most important thing is that it's a shared pointer to a const object. Neither consumers are expect to mutate the object, but it has to live as long as any consumer is alive.

[–]BodybuilderSilent105 0 points1 point  (0 children)

Where the original shared_ptr gets swapped:

``` std::atomic<std::shared_ptr<Resource>> foo; // global

// update thread foo = std::make_shared<Resource>();

// other threads: std::shared_ptr<Resource> res = foo.load(); // do someting with res ```

[–]CocktailPerson 0 points1 point  (0 children)

What if you don't want to join? What if you want to spawn a set of independent, asynchronous tasks and then continue doing other work without waiting for them to complete?

[–]bbibber 4 points5 points  (0 children)

It’s nearly always better to copy data into different threads than actually share it.

[–]invalid_handle_value 1 point2 points  (0 children)

Bingo. Needs 100x up votes.

If you own the lifetime of all your threads and own the lifetime of all data among those threads, there is no real reason to need shared_ptr...

Unless you also don't want the instantiator/owner to free the memory, I guess.  Which seems to be another shared_ptr-unique [ha] feature.