c++ - Why are the fields of the class automatic objects? -


during studing exeption's mechanism found there calls of destructors fields of object while stack's unwinding. let me explain explicitly:

class x {   file_ptr aa;   lock_ptr bb; public:  x(const char* x,const char* y):aa(x),bb(y){} //....... } 

so,now if lock_ptr's constructor throws exeption, object aa destroyed; question "why"? thought fileds of object not usual automatic (lochal) objects.they created before constructor initializes them.so can't destryed after they're out of scope of constructor (otherwise destroyed constructor's finished work)

subobjects (including non-static data members) have same storage duration complete objects belong. not same saying automatic. automatic object destroyed @ end of block. subobject destroyed whenever complete object destroyed. example, if complete object created new , destroyed delete (i.e. has dynamic storage duration), subobject created in call new, , destroyed in call delete. on other hand, subobject of automatic object automatic.

if constructor x::bb throws exception, means complete object of type x cannot constructed. subobjects have been constructed, such x::aa, must destroyed, because subobject, having same storage duration complete object, cannot survive without complete object.

on other hand, if construction of entire x object completes successfully, x::aa , other subobjects won't destroyed until (shortly after) complete x object destroyed.

the construction , destruction rules c++ intended guarantee that, long program terminates normally, every object created destroyed once. essential raii idiom. in example, if x::aa acquires resources when constructed, language must ensure resources released. if x::aa's destructor not called when construction of x fails, when should called?


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -