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?
You'll need something along the lines of:
~App::App()
{
    if (in != out)
    {
        delete out;
    }
    delete in;
}
As when the channels are different the pointers will be different.
However, as danatel has pointed out in the comments in and out are not comparable. A safe (but inelegant) solution would be to use a dummy flag. Set if in and out are set to the dummy channel, the destructor would become:
~App::App()
{
    if (!dummy)
    {
        delete out;
    }
    delete in;
}
Though I wouldn't be happy with this.
The only other solution I can see at the moment is to change the definitions of IChannelIn and IChannelOut so that they can be compared safely.
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