0

Im am currently trying to understand when to use actual objects, raw pointers and smart pointers. In the following example , which would the best to use or each step? Lets say I create and load in a image file that i want to reuse for many objects but i dont want to keep loading it from the a path using an image loading library everytime an object is created. So a single image is loaded and multiple objects can reference it. The image should also be available without any references to it until the program ends. The objects themselves either live forever or if its a particle object for example is deleted after its life is 0, without also deleting the image. Thanks.

  • 1
    Possible duplicate of [What is a smart pointer and when should I use one?](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one) – Dai Dec 11 '18 at 10:17
  • I might suggest learning Rust and its unique object lifetime semantics which eliminates a lot of the thought-processes that go into choosing pointer-types in C++. – Dai Dec 11 '18 at 10:18

1 Answers1

2

Bjarne Stroustrup recommends using smart pointers only as a last resort. His recommendations (best to worst) are:

  • Store an object by value.
  • Store many objects in a container by value.
  • If nothing else works, use smart pointers.

Plain pointers are only for referring to objects one doesn't own (the owner destroys the object). Same applies to references, although references to const and r-value references can extend the lifetime of a temporary.

See Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11, and C++14 at 0:37:40.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • So lets it would be setup as `std::vector> images `. I have two objects that uses an image in the vector so the objects would have a `Image ref` variable rather than a `Image* ref`. The image in images is not know yet until a load an image and add them to the vector, but once the objects are gone is the reference count zero and the image is deleted or is the reference count still 1 since the vector is the owner of the images? Or should I use `std::vector images` instead and place it where it would not go out of scope like in a class . Thanks for the link. –  Dec 11 '18 at 10:44
  • @DariusBigbee `std::vector` may be the best, especially if you do not resize it after it has been created. – Maxim Egorushkin Dec 11 '18 at 10:48
  • If the vector is going to be dynamically resized then the shared pointer would be better than the raw pointer correct and the objects themselves would only hold a value to it? I should also include that the objects can change images or have no image at all. –  Dec 11 '18 at 10:58