boost::weak_ptr vs pass by reference

C

Christopher

Reading on the boost pointer types, it almost sounds as if
I should always use a shared_ptr when dealing with something that is
allocated on the heap and owned
I should always use a weak_ptr when dealing with something that is
allocated on the heap, but not owned

In what cases should I be using a weak_ptr vs passing by reference?

As is, I am inclined to start replacing all those class methods that
take a reference to an object whose lifetime is managed by another
class with methods that create a weak_ptr instead. Before I do that is
there anything that I should know about using a weak_ptr vs simply
passing a reference down the line?
 
A

Alf P. Steinbach

* Christopher:
Reading on the boost pointer types, it almost sounds as if
I should always use a shared_ptr when dealing with something that is
allocated on the heap and owned
I should always use a weak_ptr when dealing with something that is
allocated on the heap, but not owned

In what cases should I be using a weak_ptr vs passing by reference?

As is, I am inclined to start replacing all those class methods that
take a reference to an object whose lifetime is managed by another
class with methods that create a weak_ptr instead. Before I do that is
there anything that I should know about using a weak_ptr vs simply
passing a reference down the line?

weak_ptr is for the case of a circular dependency, not for passing arguments.

I don't know whether its awkward interface is intentional, but I don't discount
the possibility that it is -- then to steer people away.


Cheers & hth.,

- Alf
 
J

Joe Gottman

Christopher said:
Reading on the boost pointer types, it almost sounds as if
I should always use a shared_ptr when dealing with something that is
allocated on the heap and owned
I should always use a weak_ptr when dealing with something that is
allocated on the heap, but not owned

In what cases should I be using a weak_ptr vs passing by reference?

The major uses of weak_ptr's are the following:

1) To avoid cyclic dependency.
2) To pass a reference to an object that might go out of scope or
otherwise be destructed before you use it. For example, you might use a
map<string, weak_ptr<X> > to cache all X's that were created (assuming X
has a constructor that takes a string). Then the next time you need a X
for a given string, you check whether it exists in the cache and has not
expired. If so, you reuse it and if not you create a new X and put it in
the map.


Joe Gottman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top