Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to return a C++ reference or a weak_ptr?

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?

like image 575
Doug T. Avatar asked Oct 18 '08 18:10

Doug T.


1 Answers

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.

like image 185
Michael Burr Avatar answered Sep 18 '22 16:09

Michael Burr