简体   繁体   English

从 function c++ 返回 NULL 字符串

[英]returning a NULL string from a function c++

string receiveFromServer();

this function returns a string that was received from some server.此 function 返回从某个服务器接收到的字符串。 If there was an error along the way (including protocol), i want to return a NULL string.如果一路上出现错误(包括协议),我想返回一个 NULL 字符串。 However, this doesn't work in c++ (unlike java).但是,这在 c++ 中不起作用(与 java 不同)。 i tried:我试过了:

string response = receiveFromServer();
if (response==NULL) {
    cerr << "error recive response\n";
}

but its not legal.但它不合法。 Since an empty string is also legal to return, what can i return that will indicate the error?由于返回空字符串也是合法的,我可以返回什么来指示错误?

thank you!谢谢你!

You can throw an exception to indicate an error.您可以抛出异常以指示错误。

try {
    std::string response = receiveFromServer();
} catch(std::runtime_error & e) {
    std::cerr << e.what();
}

Then you would need a throw std::runtime_error("Error receive response") somewhere in receiveFromServer() .然后你需要在receiveFromServer()某处throw std::runtime_error("Error receive response") ) 。

It is often considered good practice (though some might disagree) to create your own exception-classes that derive from std::runtime_error to enable clients to catch your errors specifically.创建您自己的从std::runtime_error派生的异常类以使客户端能够专门捕获您的错误通常被认为是一种好的做法(尽管有些人可能不同意)。

You can either throw an exception (better way), or return boost::optional< string >, but then you have to check if the return value is valid (this is actually worse).你可以抛出异常(更好的方法),或者返回 boost::optional< string >,但是你必须检查返回值是否有效(这实际上更糟)。

NULL has only a meaning when using pointers. NULL 只有在使用指针时才有意义。 In java strings are pointers so you can do that.在 java 中,字符串是指针,所以你可以这样做。

In C++, if you return an std::string, it must exist.在 C++ 中,如果返回 std::string,它必须存在。 So you have some possibilites所以你有一些可能性

  • Throw an exception抛出异常
  • Return a pair with a bool indicating the success返回一对带有表示成功的布尔值
  • Return an empty string返回一个空字符串
  • Use a pointer (I strongly discourage that option)使用指针(我强烈反对该选项)

Maybe you should try to handle with exceptions也许您应该尝试处理异常

 try
  {
    string response = receiveFromServer();
  }
  catch (...)
  {
    cerr << "error recive response\n";
  }

If you want to return an empty string you could also use the function string::empty() to test if it is empty如果你想返回一个空字符串,你也可以使用 function string::empty()来测试它是否为空

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM