Reputation: 1806
class A : boost::noncopyable{
};
class B{
A & conn() const;
};
How would i declare and implement conn() given that:
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,
Upvotes: 0
Views: 210
Reputation: 227458
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!
Upvotes: 2
Reputation: 129854
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.
Upvotes: 0
Reputation: 25799
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.
Upvotes: 1