c++ - Check for null in std::shared_ptr -
i wondering if need check whether sp
null
before use it. correct me if wrong creating alias not increase ref counter , therefore entering method working shared pointer don't know if embedded pointer has been reset before.. correct assuming this?
class::myfunction(std::shared_ptr<foo> &sp) { ... sp->do_something(); ... }
most shared pointers normal pointers in respect. have check null. depending on function, may want switch using
void myfunction( foo const& foo );
, , calling dereferencing pointer (which pushes responsibility ensuring pointer not null caller).
also, it's bad practice make function take shared pointer unless there special ownership semantics involved. if function going use pointer duration of function, neither changing or taking ownership, raw pointer more appropriate, since imposes less constraints on caller. (but depends lot on function does, , why using shared pointers. , of course, fact you've passed non-const reference shared pointer supposes going modify it, passing shared pointer might appropriate.)
finally, different implementations of shared pointers make more or less difficult check null. c++11, can use std::shared_ptr
, , compare nullptr
naturally, you'd expect. boost implementation bit broken in respect, however; cannot compare 0
or null
. must either construct empty boost::shared_ptr
comparison, or call get
on , compare resulting raw pointer 0
or null
.
Comments
Post a Comment