Tuesday, 15 February 2011

c++ - up-casting std::shared_ptr using std::dynamic_pointer_cast -



c++ - up-casting std::shared_ptr using std::dynamic_pointer_cast -

i'm starting work smart pointers in c++0x/11 , i've run peculiar situation. want cast instance of object using shared_ptr.

class extend inherits class base, base of operations class has virtual destructor in order create polymorphic (otherwise dynamic_pointer_cast complains non-polymorphic class casting).

if therefore:

std::shared_ptr<base> obj = std::make_shared<base>();

and do:

obj = std::dynamic_pointer_cast<extend>(obj); is safe ? what happens other pointers object ? obj treating extend, while other shared pointers still treat base? is safe up-cast same instance or should else ?

edit: give thanks answers. real reason asking question handle xml documents usign sax parser, got carried away up/down casting. sort of wanted was:

std::shared_ptr<extend> ex = std::dynamic_pointer_cast<extend>(obj); obj = ex;

but makes no sense @ all, instead i'll utilize object factory.

this not up-cast, down-cast (you're casting less more derived class). however:

is safe?

yes, safe, since trying downcast pointer object run-time type not extend, null pointer in return.

what happens other pointers object? obj treating extend, while other shared pointers still treat base?

you have misconception here: downcasting object doesn't transform object. if object not of target type, won't downcasted pointer it. type of pointed object (of any object) determined @ compile-time , won't change.

is safe up-cast same instance or should else ?

not sure mean here, formulation of question stems above misconception. however, instruction:

obj = std::dynamic_pointer_cast<extend>(obj);

will create obj null pointer. assignment legal, since can assign (smart) pointer derived class (smart) pointer base of operations class. however, since right side of assignment evaluates null pointer (because of written above), null pointer assigned obj.

since resetting obj, if obj lastly shared pointer object created through make_shared<>(), object destroyed after assignment above performed.

c++ c++11 shared-ptr up-casting

No comments:

Post a Comment