Returning by reference or constant link has no difference in speed - both are very fast, as they simply return a link to the original object, and copying is not performed.
The object returned by the link (not const) can be modified using this link. In your specific example, mString is publicly available, so you can change it anyway (and directly). However, the usual approach with getters and setters (and the main reason for their implementation) is encapsulation - you only allow access to your data members through the getter / setter so that you can define invalid values ββthat are set, respond to changes in values, and simply save implementation details of your class hidden inside it. Thus, recipients usually return by constant reference or by value.
However, if you return with a const link, it will link you to always keep an instance of std::string in your class to backup the link. That is, even if you later want to redesign your class so that it calculates the string "on the fly" in the getter, rather than storing it internally, you cannot. You must simultaneously change your public interface, which can break code with a class. For example, as long as you return using const-reference, this is perfectly valid code:
const std::string *result = &aSample.Get();
This code, of course, creates a dangling pointer that no longer compiles if Get() modified to return by value instead of referencing a constant. (thanks to Steve Jessop for correcting me)
To summarize, the approach I would like to take is to make mString private. Get() can be returned by value or by const reference, depending on how confident you are that you will always store the string. The class will look like this:
class sample { std::string mString; public: void Set(const std::string &s) { mString = s; } std::string Get() const { return mString; } };
Angew
source share