Search code examples
c++stringmember

Returning const std::string& vs const char* for class member


Considering the following class example :

class AClass
{
    std::string myString;

    public:
    ...
}

With one of the following accessors :

const std::string& GetMyString() const
{
    return myString;
}

versus

const char* GetMyString() const
{
    return myString.c_str();
}

Taking into account that myString is initialized once and is never changed, which accessor is better? The first one, or the second one? In what situation one of them is more suitable than its neighbor?


Solution

  • The version returning const std::string& covers a superset of the use cases for returning const char* (after all, it can be converted to the latter by calling .c_str() on the return value), with no added weaknesses. Given that std::string is more flexible in other ways, I'd prefer const std::string& of the two options.

    That said, they're both awkward if the owning object in question isn't immortal; even if the string is never changed, if the object itself disappears, the reference to its string is now invalid. If that's a possibility, you might want to either:

    1. Return by value

    or

    1. Use a std::shared_ptr<std::string> member and return that (so the lifetime of the string is no longer tied to the lifetime of the object that created it)