Returns a NULL string from a C ++ function

string receiveFromServer();

this function returns a string received from some server. If an error occurred along this path (including the protocol), I want to return a NULL string. However, this does not work in C ++ (unlike java). I tried:

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

but it is not legal. Since an empty string is also legal to return, what can I return, will this indicate an error?

Thank you!

+4
source share
5 answers

You can specify an exception to indicate an error.

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

Then you need throw std::runtime_error("Error receive response") somewhere in receiveFromServer() .

It is often considered good practice (although some may disagree) to create their own exception classes that come from std::runtime_error so that clients can specifically monitor your errors.

+9
source

You can either throw an exception (the best way) or return boost :: optional <string>, but then you have to check if the return value is correct (this is actually worse).

+5
source

NULL makes sense when using pointers. There are pointers in java strings so you can do this.

In C ++, if you return std :: string, it must exist. So you have some options

  • Throw an exception
  • Return a pair with bool indicating success
  • Returns an empty string
  • Use a pointer (I strongly discourage this option)
+1
source

Maybe you should try to handle with exceptions

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

If you want to return an empty string, you can also use the string::empty() function to check if it is empty

0
source

All Articles