1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

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,012
    Likes Received:
    203
    Trophy Points:
    0
    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