i'm reading scott meyrses' c++ , come across following code:
class lock { public: explicit lock(mutex *pm) // init shared_ptr mutex : mutexptr(pm, unlock) // point , unlock func { lock(mutexptr.get()); // see item15 info on “get” } private: std::tr1::shared_ptr<mutex> mutexptr; // use shared_ptr }; // instead of raw pointer in footnote, said code not exception-safe. in his blog proposed modify constructor of calss follows:
explicit lock(mutex *pm) { lock(pm); mutexptr.reset(pm, unlock); } that's not clear why code should work. call reset method on not yet initialized mutextptr (we removed entry ctor-initializer). why won't lie segmenetation fault?
mutexptr not uninitialized. when leave out of initializer list, default constructor called, if has one. shared_ptr has default constructor, sets held pointer null (i.e. no object managed). call reset sets manage pm. nothing deleted, because nothing held. if delete called on held pointer, delete on null pointer no-op, it's not problem.
Comments
Post a Comment