Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who should own the pointer [closed]

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.

  1. The raytracer becomes responsible of deallocating the memory allocated to the sphere object
  2. The user needs to deallocate the memory allocated to the sphere object.
  3. The raytracer just copies the sphere object and both user and raytracer deallocate their local copy.

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.

like image 791
Grieverheart Avatar asked Jan 13 '23 04:01

Grieverheart


2 Answers

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.

like image 169
Mark Ransom Avatar answered Jan 17 '23 15:01

Mark Ransom


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:

  • The user supplies the properties of the object to be added to the 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.

like image 36
jxh Avatar answered Jan 17 '23 14:01

jxh