![](/img/trans.png)
[英]What should happen when the return value from a C++ function that returns a reference of an undefined object type is not assigned?
[英]What should the return type be when the function might not have a value to return?
在过去,你可能有这样的功能:
const char* find_response(const char* const id) const;
如果找不到该项,则可以返回null以指示该事实,否则显然返回相关的字符串。
但是当函数改为:
const std::string& find_response(const std::string& id) const;
您返回什么表示未找到项目?
或者签名真的应该是:
bool find_response(const std::string& id, std::string& value) const;
什么是最优雅的现代C ++方式?
boost::optional
。 它专门针对这种情况而设计。
注意,它将作为
更新:在审查了N3690的国家机构评论后, std::optional
包含在即将推出的C ++ 14标准中。
std::optional
从C ++ 14工作文件中退出了单独的技术规范。 它不是n3797中C ++ 14草案的一部分。
与std::unique_ptr
相比,它避免了动态内存分配,并更清楚地表达了它的用途。 std::unique_ptr
更适用于多态(例如工厂方法)和将值存储在容器中。
用法示例:
#include <string>
#include <boost/none.hpp>
#include <boost/optional.hpp>
class A
{
private:
std::string value;
public:
A(std::string s) : value(s) {}
boost::optional<std::string> find_response(const std::string& id) const
{
if(id == value)
return std::string("Found it!");
else
return boost::none;
//or
//return boost::make_optional(id == value, std::string("Found it!"));
}
//You can use boost::optional with references,
//but I'm unfamiliar with possible applications of this.
boost::optional<const std::string&> get_id() const
{
return value;
}
};
#include <iostream>
int main()
{
A a("42");
boost::optional<std::string> response = a.find_response("42"); //auto is handy
if(response)
{
std::cout << *response;
}
}
什么是最优雅的现代C ++方式?
一如既往,不仅仅是这个问题的一个解决方案。
如果您决定采用任何引用原始共振实例的解决方案,那么在别名和内存管理方面,尤其是在多线程环境中,您处于一个很滑的道路上。 通过将响应复制到调用者,不会出现这样的问题。
今天,我会这样做:
std::unique_ptr<std::string> find_response(const std::string& id) const;
这样,您可以检查nullptr
为“在过去的日子里” ,并且100%清楚谁清除返回的实例是谁的责任:调用者。
我看到的唯一不足之处是响应字符串的附加副本,但是在测量和证明之前不要忽略它作为缺点。
另一种方法是在搜索std::set<>
和std::map<>
- 返回std::pair<bool, const char*>
其中一个值是bool is_found
而另一个是const char* response
。 这样你就不会得到附加响应副本的“开销”,只有返回的std::pair<>
可能会被编译器最大限度地优化。
如果函数通过引用返回一个字符串,但需要能够指示不存在这样的字符串,那么最明显的解决方案是返回一个指针,该指针基本上是一个可以为null的引用,即确切地追求的内容。
const std::string* find_response(const std::string& id) const;
这里有几个很好的解决方案。 但为了完整起见,我想补充一点。 如果您不想依赖boost::optional
您可以轻松实现自己的类
class SearchResult
{
SearchResult(std::string stringFound, bool isValid = true)
: m_stringFound(stringFound),
m_isResultValid(isValid)
{ }
const std::string &getString() const { return m_stringFound; }
bool isValid() const { return m_isResultValid; }
private:
std::string m_stringFound;
bool m_isResultValid;
};
显然你的方法签名就像这样
const SearchResult& find_response(const std::string& id) const;
但基本上与增强解决方案相同。
如果需要返回一个可空的实体,则可以原谅在C ++中使用指针。 这被广泛接受。 但当然bool find_response(const std::string& id, std::string& value) const;
很冗长。 所以这是你的选择问题。
我认为第二种方式更好。 或者你可以像这样写:
int find_response(const std::string& id, std::string& value) const;
如果此函数返回-1,则表示您没有找到响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.