Suppose I have a class where I want the user to be able to have a reference to one of my members. Which is preferred?
class Member;
class ClassWithWeakPtr
{
private:
boost::shared_ptr<Member> _member;
public:
boost::weak_ptr<Member> GetMember();
};
or
class Member;
class ClassWithCppReference
{
private:
Member _member;
public:
Member& GetMember() {return _member;}
};
What do you think? When is one better than another?
Why not return a shared_ptr<>
? Thatway the client gets to use what's returned for as long as he needs it, but there is no problem if the 'server' class goes away.
There are not too many situations where the semantics of weak_ptr<>
make a lot of sense (caches and ???). Usually when a client asks for something, it want to have ownership of that thing determined by the client itself (and shared ownership is just as good as full ownership).
If you have a situation where the 'server' object can be destroyed without knowledge of the client (a situation where you might want to use weak_ptr<>
or shared_ptr<>
) about the worst thing you can do is return a reference to a member. In this case, the client can't know whether or not it's safe to access the returned reference. You have to return a copy of the member or a smart pointer that can correctly manage the lifetime of the member being returned.
Remember that in the case where there's an expression that produces a temporary ClassWithCppReference
(which is not always obvious), the client that calls GetMember()
won't even be able to use the returned reference in the next statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With