Dynamic Memory Allocation for References

Discussion in 'C' started by rajagb4u, Aug 19, 2010.

  1. rajagb4u

    rajagb4u New Member

    Joined:
    Aug 19, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    I have a question regarding the references in C++.Can the references be allocated memory dynamically using malloc or new?
    If yes,is it required to deallocate the memory at the end?

    Prasanth
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Yes (assuming you mean "can a reference point to memory that is dynamically allocated").

    If you allocate memory with new or malloc, it is ALWAYS required to balance that with free or delete.
     
  3. LordN3mrod

    LordN3mrod New Member

    Joined:
    Sep 4, 2010
    Messages:
    22
    Likes Received:
    11
    Trophy Points:
    0
    Occupation:
    Software Developer
    Location:
    Yerevan, Armenia
    T* p = new T;
    T& r = *p;
    ///r is a reference to the dynamically allocated p here
    delete p; //ok, freeing memory
    r.dosomething;// undefined - the referent has been destroyed!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice