c++ - Why should a shared pointer be invalidated after modification? -
according herb sutter's talk in cppcon 2015, shared_ptr
should invalidated after modification,
auto sv = make_shared<vector<int>>(100); shared_ptr<vector<int>>* sv2 = &sv; vector<int>* vec = &*sv; int* ptr = &(*sv)[0]; *ptr = 1 ; vec->push_back(2); //a: modification *ptr = 5; //error: ptr invalidated "push_back" on line ptr = &(*sv)[0]; (*sv2).reset(); //b: modification vec->push_back(6); //error: vec invalidated "reset" on line b
my compiler catches none of errors. anyway, use smart pointers prevent memory leakage. what's reason suppress modification of shared_ptr
? avoid surprises? if case, can't declare const
? on other hand, if many operations on vector
can't applied because of share_ptr
, wouldn't inconvenient?
after reading comments, start understand here. modification of shared_ptr
invalidates other raw pointers pointing it.
as dyp points out in comment, push_back
might reallocate, might invalidate ptr
. if doesn't reallocate, should ptr
still valid? if reallocate, wouldn't simpler , more constructive if compiler carries buddies new territory, say, assigns raw pointers new address?
in greater context of things, herb advertising guidelines support library @ cppcon 2015 (he wasn't one).
the point trying make there exists code legal according standard, static analysis can tell problematic.
in example given here, have shared_ptr
vector
, , raw pointer pointer, , raw pointer vector held shared pointer, , raw pointer element held within vector held within shared pointer.
and did bunch of things result in undefined behavior. calls legal (call reset on shared_ptr
, attempt perform operation on vector
) in greater context of things, arguing compiler should able tell (via static analysis) did bad thing.
so in video see him these bad things no modern compiler catch, , demonstrate how compiler (in case visual studio 2015) imbued gsl will catch them.
the talk equally political informative. visual studio used because herb himself microsoft employee.this isn't bad thing; it's accepted visual studio great ide, , think message take away microsoft indeed committed c++, despite lot of moves in recent years demonstrated perhaps higher commitment c#, left c++ developers feeling second class citizens.
Comments
Post a Comment