c++ - How to avoid destroying an object on assignment / returning -
this example class:
struct peel { int* p; bool nodelete; peel() { nodelete = false; } ~peel() { if (!nodelete) delete p; } peel& operator=(const peel& other) { p = other.p; nodelete = true; } }; struct banana { peel getpeel() { peel ret; ret.p = new int(); return ret; } };
so when call
banana peelsource; auto mypeel = peelsource.getpeel();
i don't use mypeel because somewhere between return , assignment destructor of peel object gets called , while pointer copied over, allocated memory gone , invalid pointer.
why want create object this:
- in actual class, banana contains lot of information essential creation of peel , overall easier have banana build peel.
- i don't want allocate peel new , return pointer because 1 ease of peel getting automatically destroyed once goes out of scope , also, peel has bracket operator nicer without having dereference peel in brackets first.
the assignment operator attempt avoid deleting stuff never called, not sure if did right.
anyways, how make auto mypeel = peelsource.getpeel(); work without having delete data?
you write:
i don't want allocate peel new , return pointer because 1 ease of peel getting automatically destroyed once goes out of scope , also, peel has bracket operator nicer without having dereference peel in brackets first.
you might consider following. start writing peel
interface want (e.g., bracket operator). hold regular value members, without pointers, boolean flags indicating no deleteion, , forth.
struct peel { /* hold here regular value members, without pointers or boolean flags indicating whether delete, , forth.*/ // here's brackets operator. ... operator[](...); };
now use this
struct banana { peel getpeel() { peel ret; ... return ret; } };
profile see if there's problem using this. there's chance there won't be, due nrvo.
if, reason, find can't manipulate peel
objects value efficiently, consider refactoring follows. first, move heavy parts peel_imp
(again avoiding pointers , boolean flags).
// "heavy" peel stuff. struct peel_imp { /* hold here regular value members, without pointers or boolean flags indicating whether delete, , forth.*/ };
then, @edheal suggests in comments, use smart pointer hold implementation.
struct peel { ... operator[](...); std::shared_ptr<peel_imp> m_imp; };
again making peel
objects efficient value manipulation.
Comments
Post a Comment