当函数可能没有值要返回时,返回类型应该是什么? [英] What should the return type be when the function might not have a value to return?

查看:137
本文介绍了当函数可能没有值要返回时,返回类型应该是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去,你可能有这样的函数:

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

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

如果找不到项目,则可能返回null以指示事实,否则显然返回相关字符串。

If the item could not be found, then a null could be returned to indicate the fact, otherwise obviously return the relevant string.

但是当函数更改为:

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

您返回以指示未找到项目?

What do you return to indicate item not found?

或者应该签名真的是:

bool find_response(const std::string& id, std::string& value) const;

什么是最优雅的现代C ++方式?

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

推荐答案


什么是最优雅的现代C ++方式?

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


$ b b

一如既往,不只是解决这个问题的一个解决方案。

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.

今天,我会这样做:

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


$ b <

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.

另一种方式是做当搜索 std :: set<> std :: map<> code> std :: pair< bool,const char *> 其中一个值是 bool is_found ,另一个是 const char * response 。这样你不会得到额外的响应副本的开销,只有返回的 std :: pair<> 这可能是最大程度优化的编译器。

Another way is to do as is done when searching std::set<> and std::map<> - return a std::pair<bool, const char*> 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.

这篇关于当函数可能没有值要返回时,返回类型应该是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆