While programming, many times I've come across the following design choice: The user creates an object and passes it to some other object which processes in some way in a second stage.
As an example, you could imagine a raytracer. The user creates a sphere with certain properties and calls raytracer.addTraceable(sphere)
. Now, there are three ways I can think of doing this.
Generally what is the best design choice in such a case? Are there any other options besides the ones I mentioned (not including smart pointers)?
PS: I've come across the same problem in plain C when using an object oriented approach.
The consistent use of RAII makes this a moot point. Using a smart pointer such as std::shared_ptr
the object is owned by all of the pointers and it is deleted after the last pointer is destroyed.
C doesn't really have a convenient way to express the RAII idiom.
It seems you realize that a smart pointer will solve your issues for you, but that you are dismissing it for a reason you don't explain. (Maybe because your code really has to work for both C and C++?)
If the sphere
object is being managed by the raytracer
object, then logically it takes ownership of the object. However, you left out a choice that would work well for this application:
raytracer
, which is then responsible for creating and destroying the object.The raytracer
then becomes something like a factory, and the properties object is something like a builder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With