简体   繁体   中英

Delete this and then returning created object

I am creating some template class and now want to convert them to each other. I wrote function and now wondering how bad it is:

template<class ConnectionType>
class CONNECTION
{
public:
    ConnectionType weight;
    template<class FinalType> CONNECTION<FinalType>* ConvertTo()
    {
        CONNECTION<FinalType>* temp = new CONNECTION<FinalType>( );
        temp->weight = (FinalType)this->weight;
        delete this;
        return temp;
    }
    virtual ~CONNECTION() {}
};

As u Can see Iam creating new object, copy data, deleting current object and returning the new one. So now is it ok to first call delete this and after object is realased returning returning object created by method of destroyed one?

There are several things that make 'delete this' a bad idea, but one of them is that somebody will sooner or later do something like this:

Connection<Foo> foo;
Connection<Bar> * bar = foo.ConnectTo<Bar>();  // oops!

... at which point ConnectTo() will try to delete foo, and since foo was not allocated with new, undefined behavior and crashing and general unhappiness will follow.

THis is a bad idea. You are better off learning to use reference counted pointers (shared_ptr in boost or whatever the later standard call them - I am blanking at the moment). Once you do that your coding style will be transformed, life becoms clean , simple and reliable. You never code new or delete again, kittens purr, lambs gambol, ...

All joking aside - it really is a very good idiom to learn

In your case the 'old' connection object will simply be deleted when it it no longer refernced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM