c++ - Best practices - returning pointer from a function -
i have dilemma, how should return smart pointer function, when function might fail. pick 1 of following options:
- return pointer, , throw exception if function fails:
std::shared_ptr foo() { // ... if (!ok) throw; return ptr; }
- return pointer, , return empty pointer, if function fails
std::shared_ptr foo() { // ... if (!ok) return std::shared_ptr(); return ptr; }
- pass pointer reference, , return bool flag
bool foo(std::shared_ptr& ptr) { // ... if (ok) ptr = ...; return ok; }
is there best practice, guideline, how report, function didn't execute properly? or project-specific?
thanks answers
honestly correct answer depends on called function does, , consequence of failure is. libraries i'd suggest either throwing exception or returning value indicates failure. passing pointer reference , returning flag seems questionable unless you're using idiom frequently, or if there reason externally manage shared pointer.
Comments
Post a Comment