Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ delete object referenced by two pointers

Tags:

c++

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?

like image 455
danatel Avatar asked Nov 29 '22 05:11

danatel


1 Answers

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.

like image 175
ChrisF Avatar answered Dec 25 '22 16:12

ChrisF