Returning a const reference to an object instead of a copy

前端 未结 12 610
天命终不由人
天命终不由人 2020-11-29 16:40

Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:

class foo
{
private:
    std::st         


        
12条回答
  •  悲&欢浪女
    2020-11-29 17:23

    The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:

    foo *pFoo = new foo;
    const std::string &myName = pFoo->getName();
    delete pFoo;
    cout << myName;  // error! dangling reference
    

    However, since your existing function returns a copy, then you would not break any of the existing code.

    Edit: Modern C++ (i. e. C++11 and up) supports Return Value Optimization, so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok.

提交回复
热议问题