Sequencing of the copying when passing by value in C++ -
in c++, when passing object value, there restrictions on when copy takes place ?
i have following code (simplified):
class a; class parent { public: void dosomething(std::auto_ptr<a> a); // meant transfer ownership. }; std::auto_ptr<a> = ...; a->getparent()->dosomething(a); it acts like:
std::auto_ptr<a> = ...; std::auto_ptr<a> copy(a); a->getparent()->dosomething(copy); which segfault since a referencing null.
and not like:
std::auto_ptr<a> = ...; parent* p = a->getparent(); p->dosomething(a); is expected ?
a: auto_ptr deprecated in newer versions of c++, recommend checking out unique_ptr.
b: behavior expected. auto_ptr owns thing has created. if wish transfer ownership 1 auto_ptr another, original auto_ptrs managed object null pointer. though believe logic handled std::auto_ptr library , shouldn't have special behavior. if 2 auto_ptrs allowed manage same object, both try , free memory object when went out of scope. bad in itself, worse, if 1 of these auto_ptrs had broader scope attempt reference memory no longer held object in question because had since been freed other auto_ptr , in have true chaos. hence, when ownership transferred, original pointers managed object set null, , have illusion of safety. :)
Comments
Post a Comment