[英]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
所以你有一些可能性
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.