I am just curious if there is an elegant way to solve following problem in c++:
I have a simulator app which contains several components connected by channels. The channels may be either network channels (two instances of the app are needed) or dummy local channel. There are two interfaces: IChannelIn and IChannelOut and two corresponding variables:
IChannelIn* in;
IChannelOut* out;
The DummyChannel is both IChannelIn and IChannelOut. It just copies input to output. There is also TCPChannelIn: public IChannelIn and separate TCPChannelOut: public IChannelOut.
Now, according to user’s choice , I either create one DummyChannel
DummyChannel* d = new DummyChannel;
in = d;
out = d;
or two separate objects: in = new TCPChannelIn; out = new TcpChannelOut
The question is: what should the destructor do?
~App::App()
{
delete in;
delete out;
}
ends in an error because delete in; deleted also the dummy channel d so that delete out deletes already deleted thing.
Is there an elegant way out of this?
How does your class know that this is a freestore pointer? E.g. what speaks against the following code?
This is an entirely sensible piece of code but your destructor will crash when trying to delete either of the pointers.
Long story short: reclaiming resources is the job of whoever has allocated the resources in the first place. If your class gets passed a pointer, the class cannot know and does not care about deallocation. This is strictly the responsability of the caller.
Elegant ways to solve this dilemma without making the client to a lot of work are smart pointers, as mentioned before.