c++ - Delete this and then returning created object -
i creating template class , want convert them each other. wrote function , wondering how bad 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; homecoming temp; } virtual ~connection() {} }; as u can see iam creating new object, re-create data, deleting current object , returning new one. ok first phone call delete , after object realased returning returning object created method of destroyed one?
there several things create 'delete this' bad idea, 1 of them sooner or later this:
connection<foo> foo; connection<bar> * bar = foo.connectto<bar>(); // oops! ... @ point connectto() seek delete foo, , since foo not allocated new, undefined behavior , crashing , general unhappiness follow.
c++ object return this delete-operator
No comments:
Post a Comment