boost:shared_ptr ::weak_ptr using with NULL?

R

Raf256

Hi,
how to convert following C++ code:

foobar *ptr = new foobar(5);
//...
if (something()) ptr = NULL;
if (!ptr) return no_object_is_selected_apparently;
// ...
if (!ptr) throw oh_shit_no_object; // ?!
else ptr->Fun();

...using weak_ptr and shared_ptr.
Something like...

// 1)
shared_ptr<foobar) ptr( new foobar(5) );
if (something) pre.reset();
if (!ptr) return no_object_is_selected_apparently;
if (!ptr) throw oh_shit_no_object;
else ptr->Fun();

// 2)
weak_ptr<foobar) ptr( new foobar(5) );
if (something) pre.reset();
if (ptr.expired()) return no_object_is_selected_apparently;
ptr.lock()->Fun(); // lock will throw if needed

Is the code above o.k.?
 
H

Howard Hinnant

Hi,
how to convert following C++ code:

foobar *ptr = new foobar(5);
//...
if (something()) ptr = NULL;
if (!ptr) return no_object_is_selected_apparently;
// ...
if (!ptr) throw oh_shit_no_object; // ?!
else ptr->Fun();

..using weak_ptr and shared_ptr.
Something like...

// 1)
shared_ptr<foobar) ptr( new foobar(5) );
if (something) pre.reset();
if (!ptr) return no_object_is_selected_apparently;
if (!ptr) throw oh_shit_no_object;
else ptr->Fun();

This looks fine to me. But it also looks like overkill, at least in
this limited scope. std::auto_ptr would probably be better if you don't
really need shared ownership semantics.
// 2)
weak_ptr<foobar) ptr( new foobar(5) );
if (something) pre.reset();
if (ptr.expired()) return no_object_is_selected_apparently;
ptr.lock()->Fun(); // lock will throw if needed

Is the code above o.k.?

You may have an old version of boost. The current weak_ptr (including
the TR1 version) does not have a constructor that takes a pointer. You
can construct one from a shared_ptr though.

-Howard
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top