简体   繁体   English

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

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

I do this a lot in Java... 我在Java中做了很多...

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

Now I'm trying to find an equivalent approach for std::string . 现在我正在尝试为std::string找到一个等价的方法。 Here is what I have... 这是我的......

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

For completeness, here is what aFunctionThatMightThrowAnException() might look like... 为了完整性,这里是aFunctionThatMightThrowAnException()可能看起来像...

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

I have three questions about the C++ version: 我有三个关于C ++版本的问题:

  • Is this an accepted approach to this kind of problem? 这是解决这类问题的方法吗? Or is it more common to pass the something into aFunction as a reference? 或者将something aFunction作为参考传递给aFunction更常见?
  • Is my assignment to something as the return from aFunction... safe? 我的任务something作为从aFunction...返回的aFunction...安全吗? Specifically is the memory that was originally assigned to "A default value." 具体是最初分配给"A default value."的内存"A default value." released? 释放?
  • Are there side effects I can't see in the case an exception is thrown? 在抛出异常的情况下是否有我无法看到的副作用?

Is this an accepted approach to this kind of problem? 这是解决这类问题的方法吗?

Yes. 是。

Or is it more common to pass the something into aFunction as a reference? 或者将某些内容作为参考传递给aFunction更常见?

No. 没有。

Is my assignment to something as the return from aFunction... safe? 我的任务是作为从函数返回的东西......安全吗? Specifically is the memory that was originally assigned to "A default value." 具体是最初分配给“默认值”的内存。 released? 释放?

Yes. 是。

Are there side effects I can't see in the case an exception is thrown? 在抛出异常的情况下是否有我无法看到的副作用?

No. 没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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