returning reference from method

三世轮回 提交于 2019-12-12 03:11:03

问题


class A : boost::noncopyable{
}; 
class B{
    A & conn() const;
};

How would i declare and implement conn() given that:

  • conn should create and return a reference to an object of type A.
  • i can't break B's interface in client code using B.
  • i want to prevent my code to leak memory, so i cannot simply return references to objects in heap.

I didn't find any implementation of smart pointers that wouldn't break client code since there's no conversion to type A*, and i left client code untouched then i'd have memory leaks.

Sincerely,


回答1:


You could satisfy your three requirements by having conn() create a smart pointer (std::unique_ptr would suit this case) to a new A, place it in a data member container of such smart pointers, and return a reference to the object managed by the smart pointer. You would have to declare the container mutable though, since your conn() method is const. I am not saying it is a good design though, just a was to meet your requirements. For example, using c++11:

class B {

 public:
  inline A& conn() const {
    data_.emplace_back(new A);
    return *(data_.back().get());
  }

 private:
  mutable std::vector<std::unique_ptr<A>> data_;
};

The lifetime of all the A objects is bound to B. BTW bear in mind that your interface provides non-const references to A objects, via a const method. This is not very good!




回答2:


Return a reference to a function-level static object:

A& b::conn( ) const
{
    static A theA;
    return theA;
}

I'm not advocating that this is a good thing to do but it's one way of solving the problem.




回答3:


You have to add A instance as a data member of B to be able to return a reference (or use a static instance inside conn, but that brings a ton of trouble and should be avoided like fire). This doesn't break the API, but it will break the ABI.



来源:https://stackoverflow.com/questions/9684296/returning-reference-from-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!