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

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -