从可能引发异常的函数返回 std::string

Returning a std::string from a function that might throw an exception

本文关键字:函数 返回 std string 异常      更新时间:2023-10-16

我在Java中做了很多...

String something = "A default value.";
try {
    something = this.aFunctionThatMightThrowAnException();
} catch (Exception ignore) { }
this.useTheString(something);

现在我正在尝试为std::string找到一种等效的方法。 这是我所拥有的...

std::string something("A defualt value.");
try {
    something = this->aFunctionThatMightThrowAnException();
} catch (const std::exception& ignore) { }
this->useTheString(something);

为了完整起见,以下是aFunctionThatMightThrowAnException()可能的样子...

std::string MyClass::aFunctionThatMightThrowAnException() {
    /* Some code that might throw an std::exception. */
    std::string aString("Not the default.");
    return aString;
}

关于C++版本,我有三个问题:

  • 这是解决此类问题的公认方法吗? 还是将something传递给aFunction作为参考更常见?
  • 我从aFunction...返回的something作业安全吗? 具体来说,最初分配给"A default value."的内存是否已发布?
  • 引发异常的情况下,是否有我看不到的副作用?

这是解决此类问题的公认方法吗?

是的。

还是将某些东西传递给 aFunction 作为引用更常见?

不。

我的分配是作为函数的回报...安全?具体来说,最初分配给"默认值"的内存是否释放?

是的。

引发异常的情况下,是否有我看不到的副作用?

不。