What happens if I return literal instead of declared std::string?

前端 未结 2 514
广开言路
广开言路 2021-01-12 07:05

Say we have an utility function:

std::string GetDescription() { return \"The description.\"; }

Is it OK to return the string literal? Is th

相关标签:
2条回答
  • 2021-01-12 07:10

    Is it OK to return the string literal? Is the implicitly created std::string object copied?

    It is OK. What you get, is the (implicit) constructor for std::string, creating a local copy, returned then as a rvalue reference. Taking the result in client code into a string, will set that string from an rvalue reference.

    If you use the second piece of code, you "say too much". The code is correct, and they are (almost) equivalent (they should be equivalent, but the optimizations that the compiler is permitted to perform in the first case are better*).

    I would go for:

    std::string GetDescription() { return std::string("The description."); }
    

    This way it is explicit that you return a string, and the code is (almost) minimal: you rely on the std::string move-construction.

    *) edited accordingly, after comment by @SteveJessop.

    0 讨论(0)
  • 2021-01-12 07:18
    std::string GetDescription() { return "XYZ"; }
    

    is equivalent to this:

    std::string GetDescription() { return std::string("XYZ"); }
    

    which in turn is equivalent to this:

    std::string GetDescription() { return std::move(std::string("XYZ")); }
    

    Means when you return std::string("XYZ") which is a temporary object, then std::move is unnecessary, because the object will be moved anyway (implicitly).

    Likewise, when you return "XYZ", then the explicit construction std::string("XYZ") is unnecessary, because the construction will happen anyway (implicitly).


    So the answer to this question:

    Is the implicitly created std::string object copied?

    is NO. The implicitly created object is after all a temporary object which is moved (implicitly). But then the move can be elided by the compiler!

    So the bottomline is this : you can write this code and be happy:

    std::string GetDescription() { return "XYZ"; }
    

    And in some corner-cases, return tempObj is more efficient (and thus better) than return std::move(tempObj).

    0 讨论(0)
提交回复
热议问题