c++ - Calling a method that doesn't access data on a null object pointer sometimes works, sometimes crashes. Why doesn't it always crash? -
let's have class:
class magicalmysteryclass { public: dosomethingwithouttouchinginstancedata() { usleep(1000); } private: int somedata; }
and seek phone call method via null pointer:
magicalmysteryclass *obj = 0; obj->dosomethingwithouttouchinginstancedata();
on 1 machine of mine, errant phone call works 90% time. on machine, crashes 90% of time.
why work @ all?
if cannot reliably expect phone call null pointer behave in consistent manner, how can projected myself against this?
if want protect against accidental usage of null pointer, can create own smart pointer class throws error if seek dereference it.
template<typename t> class protectedptr { public: protectedptr(t* p = nullptr) : ptr(p) { } t& operator*() { if (ptr == nullptr) throw std::runtime_error("attempt dereference null pointer"); homecoming *ptr; } t* operator->() { if (ptr == nullptr) throw std::runtime_error("attempt dereference null pointer"); homecoming ptr; } private: t* ptr; };
c++
No comments:
Post a Comment