C++ null字符串

0 c++

我在C++程序中有一个函数返回一个string.在某些情况下,例如,如果函数遇到错误左右,我想返回一个特殊值,告诉调用者出错的地方.

我基本上只能返回一个空字符串"",但该函数确实需要空字符串作为正常的返回值.

  • 我怎么能做到这一点?
  • 我是否已经为我的函数创建了一个特殊的数据结构,如果函数成功运行并且包含实际返回值的字符串,它将保存bool?

Joh*_*itb 10

这听起来像是异常的用例.

try {
  std::string s = compute();
} catch(ComputeError &e) {
  std::cerr << "gone wrong: " << e.what();
}
Run Code Online (Sandbox Code Playgroud)

如果您不想或不能使用异常,则可以更改功能的界面

std::string result;
if(!compute(result)) {
  std::cerr << "Error happened!\n";
}
Run Code Online (Sandbox Code Playgroud)

虽然大多数情况下,我已经看到返回值用于实际结果,并传递错误指针

bool b;
std::string s = compute(&b);
if(!b) {
  std::cerr << "Error happened!\n";
}
Run Code Online (Sandbox Code Playgroud)

这样做的好处是你可以默认错误参数指针0和可以忽略错误的代码(例如,因为它可以使用空字符串返回,或者如果它事先知道输入有效)就不需要打扰:

std::string compute(bool *ok = 0) {
  // ... try to compute

  // in case of errors...
  if(ok) {
    *ok = false;
    return "";
  }

  // if it goes fine
  if(ok) {
    *ok = true;
  }
  return ...;
}
Run Code Online (Sandbox Code Playgroud)