Results 1 to 6 of 6

Thread: reference to a pointer example and pitfalls

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    thinBasic MVPs kryton9's Avatar
    Join Date
    Nov 2006
    Location
    Naples, Florida & Duluth, Georgia
    Age
    68
    Posts
    3,865
    Rep Power
    405

    reference to a pointer example and pitfalls

    In Java you can use the New operator to create an object from Free System Memory and assign it to a Reference. In C++ you have to use New with Pointers.
    I thought well, what if I make a reference to the pointer and then delete it to avoid memory leaks later. I thought this would a be a cool work around, but alas it didn't work.
    PHP Code:
    #include <iostream>

    using namespace std;

    class 
    v3
    {
        private:
            
    int x;
            
    int y;
            
    int z;


        public:
        
    v3(int X 0int Y 0int Z 0)
        {
            
    X;
            
    Y;
            
    Z;
        }


        
    void print( void )
        {
            
    cout << "x: " << << "    y: " << << "    z: " << << "\n";
            
    cout << "\n\n\n\n";
        }
    };


    int main()
    {
        
    cout << " Program memory v3 variable v" << "\n\n";
        
    v3 v362436 );
        
    v.print();


        
    v3vp = new v3442740 );
        
    cout << " Free memory using new operator creating pointer vp" << "\n\n";
        
    vp->print();


        
    v3vr = *vp;
        
    cout << " vr reference to the pointer vp" << "\n\n";
        
    vr.print();


        
    delete vp;
        
    cout << " Deleted pointer vp to avoid memory leaks" << "\n\n\n\n";


        
    cout << " Our reference vr has garbage now" << "\n\n";
        
    vr.print();


        
    cout << " Shame that you can't use the new operator with references in c++" << "\n";
        
    cout << " like you can in Java. I thought perhaps this work around would have worked" << "\n";
        
    cout << " but it didn't." << "\n\n";


        
    cout << " Press Enter to Exit" << "\n\n";

        
    cin.get();

        return 
    0;

    Last edited by kryton9; 20-06-2011 at 03:20.

Similar Threads

  1. Irrlicht reference
    By ErosOlmi in forum Irrlicht
    Replies: 1
    Last Post: 05-05-2007, 02:13

Members who have read this thread: 0

There are no members to list at the moment.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •