Class API design: should I return a field in getXxx() method by value or as a const-ref?
Just a C++ newbie question. I have a class like
class Person
{
private:
std::string m_name;
};
Is it bet开发者_StackOverflowter to design getter as
std::string name() const;
so m_name will be copied each time name() is called or as
const std::string& name() const;
so caller can make his own copy, if he wants.
In general, I would go with the const& version, since it avoids unnecessary copying.
However, if you're making a class that's intended to be accessed by multiple threads simultaneously, returning a copy is cleaner and more reliable.
The general rule is to return by value unless it is part of the contract that you return a reference to something internal (e.g. like vector<>::operator[]). In addition to threading issues, there can easily be lifetime of object issues: if you return a reference, and the client captures it by reference, then deletes your object, he's left with a dangling reference.
Return by value does have performance implications. If these become a concern, you might want to return by an out argument, which will also avoid a copy of the filled out object, e.g.: void tables(std::vector* result); I wouldn't do this until I knew I had a performance problem, however.
The fact that it's possible to return a reference is dependent on something that's probably an implementation detail, that name
is stored in the objects as a std::string
. Conceivably it could be stored differently (perhaps via a char*, or compressed, or in a different character encoding from the one that your name
function says that it returns), and converted to std::string
on the fly.
So, do you want to bake this implementation detail into your interface? If not, then you shouldn't even consider returning a reference.
精彩评论