简体   繁体   中英

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

I do this a lot in 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 . 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...

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:

  • Is this an accepted approach to this kind of problem? Or is it more common to pass the something into aFunction as a reference?
  • Is my assignment to something as the return from aFunction... safe? Specifically is the memory that was originally assigned to "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?

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.

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