Returning a const reference to an object instead of a copy

前端 未结 12 601
天命终不由人
天命终不由人 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:43

    One problem for the const reference return would be if the user coded something like:

    const std::string & str = myObject.getSomeString() ;
    

    With a std::string return, the temporary object would remain alive and attached to str until str goes out of scope.

    But what happens with a const std::string &? My guess is that we would have a const reference to an object that could die when its parent object deallocates it:

    MyObject * myObject = new MyObject("My String") ;
    const std::string & str = myObject->getSomeString() ;
    delete myObject ;
    // Use str... which references a destroyed object.
    

    So my preference goes to the const reference return (because, anyway, I'm just more confortable with sending a reference than hoping the compiler will optimize the extra temporary), as long as the following contract is respected: "if you want it beyond my object's existence, they copy it before my object's destruction"

提交回复
热议问题