c++ - design headache with unique_ptr -


say have class foo:

class foo { public:   ... }; 

foo has instance method either transforms foo instance foo instance, or returns same foo instance:

<some appropriate pointer type foo> foo::trytotransform() {   if (canbetransformed()) {     <delete foo instance>;     return <new instance of foo>;   }   else {     return <this instance of foo>;   } } 

client code:

<some appropriate pointer type foo> foo = ...; ... foo = foo->trytotransform(); 

this easy naked pointers:

foo* foo::trytotransform() {   if (canbetransformed()) {     delete this;     return new foo(...);   }   else {     return this;   } }  foo* foo = ...; ... foo = foo->trytotransform(); 

but if client code uses unique_ptr instead of naked pointer? is, ideally client code this:

unique_ptr<foo> foo = ...; ... foo = foo->trytotransform(); 

how should foo::trytotransform() defined in order enable such (or similar) client code?

because trytotransform function member function, caller retains ownership of unique_ptr. therefore impossible (without dirty tricks) delete caller's unique_ptr inside member function.

therefore, need static function takes ownership of unique_ptr:

class foo {     static unique_ptr<foo> trytotransform(unique_ptr<foo> ptr) {         if(...) {             return unique_ptr<foo>(new foo()); // old ptr destroyed         } else {             return ptr;     } }; 

call as

unique_ptr<foo> foo = ...; ... foo = foo::trytotransform(move(foo)); 

this works having trytotransform take ownership of unique_ptr. able destroy pointer wishes.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -