What should the return type be when the function might not have a value to return?

后端 未结 6 971
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 17:25

In the old days, you might have a function like this:

const char* find_response(const char* const id) const;

If the item could not be found

6条回答
  •  伪装坚强ぢ
    2021-01-01 17:55

    What would be the most elegant modern C++ way?

    There's, as always, not just one solution to this problem.

    If you decide to go for any solution that references the original resonse instance, you're on a slippery road when it comes to aliasing and memory management, especially in a multi threaded environment. By copying the response to the caller, no such issues arises.

    Today, I would do this:

    std::unique_ptr find_response(const std::string& id) const;
    

    That way, you can check for nullptr as "in the olden days" and it's 100% clear who's responsibility it is to clear up the returned instance: the caller.

    The only downside I see of this, is the additional copy of the response string, but don't dismiss that as a downside until measured and proven so.

    Another way is to do as is done when searching std::set<> and std::map<> - return a std::pair where one value is bool is_found and the other is const char* response. That way you don't get the "overhead" of the additional response copy, only of the returned std::pair<> which is likely to be maximally optimized by the compiler.

提交回复
热议问题