c++c++11return-typereturn-by-referencereturn-by-value

What is better: return std::string by value or by constant reference?


Here is a class with two getters with different return type:

class A {
    std::string m_test { "test" };

public:
    std::string test_by_value { return m_test; }
    const std::string& test_by_const_ref() { return m_test; }
};

// ...

Which is better? It is about std::string, not built-in types. Is S.T.L. says in https://channel9.msdn.com/Events/GoingNative/2013/Don-t-Help-the-Compiler that it is better to return by value, because multiple copies will be optimized? Or am I incorrectly understanded him?


Solution

  • By value.

    I encountered similar code in the wild:

    A foo();
    
    std::string const& x = foo().test_by_const_ref();
    

    Boom, x is a dangling reference.

    That does not happen with returns by value.