When should you return a reference to a object from a class method

后端 未结 7 1754
旧时难觅i
旧时难觅i 2021-02-14 01:14

What is the best practice for returning references from class methods. Is it the case that basic types you want to return without a reference whereas class objects you want to r

7条回答
  •  太阳男子
    2021-02-14 01:43

    I would recommend staying away from returning references for the same reason as Iraimbilanja points out, but in my opinion you can get very good results by using shared pointers (e.g., boost, tr1) on the member data and use those in return. That way you do not have to copy the object but can still manage life time issues.

    class Foo
    {
    private:
        shared_ptr _bar;
    public:
        shared_ptr getBar() {return _bar;}
    };
    

    Usually the cost of copying Bar is greater than the cost of constructing new shared_ptrs, should this not be the case it can still be worth using for life time management.

提交回复
热议问题