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

Discussion in 'C++' started by phlip, Jul 8, 2008.

  1. phlip

    phlip Guest

    Nick Keighley wrote:

    >>> 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?

    >> return * my_pointer;
    >>
    >> ?
    >>
    >> * is pronounced "dereference"...

    >
    > 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?


    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
     
    phlip, Jul 8, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Philippe Guglielmetti
    Replies:
    4
    Views:
    903
    tom_usenet
    Oct 9, 2003
  2. James Mastro

    boost::shared_ptr inside stl::list

    James Mastro, Nov 13, 2003, in forum: C++
    Replies:
    1
    Views:
    2,041
    Cy Edmunds
    Nov 13, 2003
  3. Derek
    Replies:
    2
    Views:
    629
    Derek
    Dec 8, 2003
  4. Toby Bradshaw
    Replies:
    6
    Views:
    1,767
    Kai-Uwe Bux
    Jun 2, 2006
  5. Colin Caughie
    Replies:
    1
    Views:
    725
    Shooting
    Aug 29, 2006
Loading...

Share This Page