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:

  1. return pointer, , throw exception if function fails:
      std::shared_ptr foo() {         // ...         if (!ok)           throw;         return ptr;     }  
  1. return pointer, , return empty pointer, if function fails
      std::shared_ptr foo() {         // ...         if (!ok)             return std::shared_ptr();          return ptr;     }  
  1. 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

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -