Problems copying object pointer

Discussion in 'C++' started by Angus, Apr 11, 2008.

  1. Angus

    Angus Guest

    I have a function called subscribe which passes a pointer to a
    'subscribing' object to a class which will call functions on this
    object.

    Here is the function:
    void CEventSelect::subscribe(CEventSelect* user)
    {
    m_subscriber = user
    m_coll.push_back(user);
    }

    I declare this member like this:

    CMySubscriber* m_subscriber;

    If I copy using = in this way, m_subscriber becomes invalid as soon as
    the subscribe function finishes.

    If I put object in eg a vector then it works fine. Because I suppose
    vector is doing a proper copy. How would I do a sim,ilar copy without
    having to use a vector?
     
    Angus, Apr 11, 2008
    #1
    1. Advertising

  2. Angus

    Boris Glawe Guest

    Angus schrieb:
    > I have a function called subscribe which passes a pointer to a
    > 'subscribing' object to a class which will call functions on this
    > object.
    >
    > Here is the function:
    > void CEventSelect::subscribe(CEventSelect* user)
    > {
    > m_subscriber = user
    > m_coll.push_back(user);
    > }
    >
    > I declare this member like this:
    >
    > CMySubscriber* m_subscriber;
    >
    > If I copy using = in this way, m_subscriber becomes invalid as soon as
    > the subscribe function finishes.


    Why will m_subscriber become invalid?

    The method CEventSelect::subscriber gets only a pointer. At the end of
    the scope of the subscribe method, the pointer will be deleted, but not
    the user object itself. As you have copied the pointer to m_subscriber,
    there is no obvious reason,why it should become invalid!?


    >
    > If I put object in eg a vector then it works fine. Because I suppose
    > vector is doing a proper copy. How would I do a sim,ilar copy without
    > having to use a vector?


    If you have problems you have to post more code in order to specify the
    reason for your problems.

    greets Boris
     
    Boris Glawe, Apr 11, 2008
    #2
    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. Replies:
    10
    Views:
    742
    Chris Torek
    Feb 4, 2005
  2. jimjim
    Replies:
    16
    Views:
    876
    Jordan Abel
    Mar 28, 2006
  3. , India
    Replies:
    1
    Views:
    700
    Pascal J. Bourguignon
    Apr 22, 2008
  4. Replies:
    4
    Views:
    1,330
    Fred Zwarts
    Jul 2, 2009
  5. Sparhawk
    Replies:
    5
    Views:
    125
    Harag
    Aug 29, 2004
Loading...

Share This Page