c++ - Should ownership be ended before or after stl containers call its value's destructor? -
c++ - Should ownership be ended before or after stl containers call its value's destructor? -
in next code, x registered in global container becomes shared owner of it. destructor of x tests no longer part of such ownership anymore, expect valid precondition getting destroyed.
#include <vector> #include <memory> struct x { ~x(); }; std::vector<std::shared_ptr<x> > global_x_reg; x::~x() { (auto iter = global_x_reg.begin(), end = global_x_reg.end(); iter != end; ++iter) if (iter->get() == this) throw "oops. x gets destroyed while still owned!"; } int main(int argc, char** argv) { global_x_reg.push_back( std::shared_ptr<x>(new x) ); global_x_reg.clear(); // calls x::~x(). }
when runs (after compilation vs2010), "oops..." thrown when container cleared.
questions:
is code legal? if not, why not? if so, should throw? should std container implementclear()
in such way during destruction of values, these values no longer visible containees. should std::shared_ptr::get
, when std::shared_ptr
destroying pointee, homecoming nullptr
?
per n3936 [basic.life]/1: "the lifetime of object non-trivial initialization ends when destructor phone call starts.", , /3:
the properties ascribed objects throughout international standard apply given object during lifetime. [ note: in particular, before lifetime of object starts , after lifetime ends there important restrictions on utilize of object, described below, in 12.6.2 , in 12.7. also, behavior of object under construction , destruction might not same behavior of object lifetime has started , not ended. 12.6.2 , 12.7 describe behavior of objects during construction , destruction phases. —end note ]
you invoking fellow member function on shared_ptr
after end of lifetime. since there's no way know if given standard library class fellow member function complies restrictions specified, invoking fellow member function on standard library object after end of lifetime consequently has undefined behavior unless otherwise specified.
see library working grouping issue 2382 "unclear order of container update versus object destruction on removing object", pertains much question. in general, it's not thought re-enter standard library object (global_x_reg
) while in middle of processing fellow member function phone call (global_x_reg.clear()
in case). class invariants must hold before , after fellow member call, there no guarantee object in valid state during call.
c++ c++11 st
Comments
Post a Comment