Andrew
Andrew

Reputation: 1621

C++ - Allocating on heap than using new object as reference to maintain interface

I have a case in my application where I need to create a new object dynamically based on what type info I get back from an external source. Basically, I have class A that handles this task. The class will either create class B, C, or D, etc. (say B is the base and C and D are derived types). Then I want to pass this object to an existing interface that is full of methods that expect a reference parameter of type B. Eventually this dynamically allocated object is stored in a boost::shared_ptr member object of another class (I use the reset() method on the shared_ptr). So at that point the memory is being managed by someone.

Basically it seems like this is bad design to me (that I'm passing this dynamically allocated object all over the place, dereferencing it at one point and then getting the pointer to it again later). On the other hand, I don't want to change several methods of an interface to take a pointer rather than a reference. I would like to leave that interface alone and dereference the pointer when I'm passing the object on to the interface for further processing. I read somewhere that when you have a method that takes a reference parameter, you're saying "I'm not concerned about memory management here" and "this object will be initialized - i.e. can't be NULL". The object was originally created on the heap though and will eventually be "owned" by another class that will manage its memory. Is still OK to have these interface methods take reference parameters in this case?

Upvotes: 3

Views: 1513

Answers (1)

paddy
paddy

Reputation: 63481

I think that the primary goal of design in terms of object usage and lifetime should be that the ownership of the object is clear and well-understood at all times. The creation and deletion is ideally handled in only one place, or is clearly signposted when you are creating and handing-off somewhere else - again, that should be done only in one place.

My preference would be that until the object is owned outright by some piece of code, then pointers should be used. Once it is owned, then the owner can pass it on as a reference.

  • With pointers, it's okay to interpret as "here's an object - does anyone want it?"
  • With references, you're saying "here's MY object - you can use it"

But if that forces you to makes the rest of your code ugly and confusing, then maintaining that ideal is not worth the price you pay. If you can at least make the creation and hand-off look clean, then you can hide the quirky stuff in some other (well-documented) part of the code...

B * myInst = A::BFactory( current_state_of_universe );
bool bSubmitted = SubmitForMagic( myInst );
if( !bSubmitted ) delete myInst;

Upvotes: 1

Related Questions