简体   繁体   中英

returning a NULL string from a function c++

string receiveFromServer();

this function returns a string that was received from some server. If there was an error along the way (including protocol), i want to return a NULL string. However, this doesn't work in c++ (unlike 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() .

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.

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).

NULL has only a meaning when using pointers. In java strings are pointers so you can do that.

In C++, if you return an std::string, it must exist. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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