当函数没有返回值时,返回类型应该是什么?

Ang*_*ber 17 c++

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

const char* find_response(const char* const id) const;
Run Code Online (Sandbox Code Playgroud)

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

但是当函数改为:

const std::string& find_response(const std::string& id) const;
Run Code Online (Sandbox Code Playgroud)

您返回什么表示未找到项目?

或者签名真的应该是:

bool find_response(const std::string& id, std::string& value) const;
Run Code Online (Sandbox Code Playgroud)

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

mil*_*bug 22

boost::optional.它专门针对这种情况而设计.

注意,它将包含在即将推出的C++ 14标准中std::optional.更新:在审查了N3690的国家机构评论之后,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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ell 5

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

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

如果您决定寻求引用原始共振实例的任何解决方案,那么在别名和内存管理方面,尤其是在多线程环境中,您处于一个很滑的道路上.通过将响应复制到调用者,不会出现这样的问题.

今天,我会这样做:

std::unique_ptr<std::string> find_response(const std::string& id) const;
Run Code Online (Sandbox Code Playgroud)

这样,您可以检查nullptr"在过去的日子里" ,并且100%清楚谁清除返回的实例是谁的责任:调用者.

我看到的唯一的缺点是响应字符串的附加副本,但是在测量和证明之前不要忽略它作为缺点.

另一种方法是在搜索时执行,std::set<>std::map<>返回std::pair<bool, const char*>一个值为另一个值bool is_found的位置const char* response.这样你就不会得到附加响应副本的"开销",只有返回std::pair<>的可能会被编译器最大限度地优化.