Tech Support > Computers & Technology > Programming > how do I convert back a boost shared_ptr into a reference?
how do I convert back a boost shared_ptr into a reference?
Posted by Luna Moon on July 6th, 2008


how do I convert back a boost shared_ptr into a reference?

The function is as follows:

const myclass& myfunc() const
{

//I have a boost shared_ptr here;
// but I have to return "const myclass &"
}

How to do that?

Thanks!

Posted by phlip on July 6th, 2008


Luna Moon wrote:
return * my_pointer;

?

* is pronounced "dereference"...

Posted by Nick Keighley on July 8th, 2008


On 6 Jul, 18:30, phlip <phlip2...@gmail.com> wrote:
will code like this cause a problem

const myclass& myfunc() const
{
boost::shared_ptr<myclass> my_pointer (new myclass());
return *my_pointer;
}

will the newsed object be destroyed as the shared_ptr
goes out of scope? If not when does it get destroyed?

--
Nick Keighley




Posted by phlip on July 8th, 2008


Nick Keighley wrote:

CC'd to the correct newsgroup.

Yes, the destructor of the shared pointer will delete the object. Then its
former address will convert to a reference. At some point - possibly the
conversion - Undefined Behavior will begin. And then when whoever collects the
reference uses it, Undefined Behavior will continue.

Why are you trying to do this? myfunc should just return a shared_ptr...

--
Phlip


Similar Posts