Home > Net >  "const std::string &getStr" vs "std::string getStr"
"const std::string &getStr" vs "std::string getStr"

Time:11-22

Can someone explain in simple words

why a developer did the following

const std::string &getStr() const
{
    return m_Str;
}

instead of

std::string getStr() const
{
    return m_Str;
}

CodePudding user response:

That's two separate things. The second example returns a copy of the member variable m_Str, the first one a constant reference to the same variable. The difference is quite noticeable, if you take a look at the caller of this method. Imagine another method setStr that changes the member variable. Now take a look at the following code:

instance.setStr("Foo");
const std::string& str = instance.getStr();
instance.setStr("Bar");
std::cout << str << std::endl; // Prints "Bar".

Whereas if you return a copy, the output will be different:

instance.setStr("Foo");
std::string str = instance.getStr();
instance.setStr("Bar");
std::cout << str << std::endl; // Prints "Foo".

CodePudding user response:

The second version will cause a copy of m_Str while the function returns, and that could unnecessarily reduce the performance each time calling the function. Returning a reference to const to it can easily solve this problem and eliminate redundant copy construct of temporary objects.

Yes, returning a const reference is not very common, if the function is just a normal non-member function, trying to returning a reference to it's local object would definitely cause a disaster, because the lifetime of the local object will end at the returning of the function. But a member function returning a member variable of this is a exception, the member variable is not a local object of the function, so returning it is all okay.

  •  Tags:  
  • c
  • Related