Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

PHP: Deleted but still remains

  1. Mar 10, 2015 #1
    Code (C):

    using namespace std;
    class A
    {
       int i;
    public:
       A();
       void Set(int& i){this->i=i;}
       void Print(){cout<<i<<endl;}
    };

    int main()
    {
       int *i=new int;
       A ra;
       i=10;
       ra.Set(*i);
       delete i;
       ra.Print();
    }
     
    I think after delete i, the value in Set will also be deleted. Isn't Set(int &) means to pass in it by reference ?
     
    Last edited by a moderator: Mar 11, 2015
  2. jcsd
  3. Mar 10, 2015 #2
    Soo sorry I post in the wrong forum. It should be the Programming forums up there. :nb)
    Thank you any way:bow:
     
  4. Mar 11, 2015 #3

    Mark44

    Staff: Mentor

    It's hard to tell what you're trying to do. It seems to me to be very bad programming practice to use i for two completely different purposes. In class A, i is a private member of type int, but in main, i is a pointer to an int. Programmers almost always use i as a loop control variable.

    What is the purpose of this line in main?
    i = 10;
    After all, i is a pointer in main.
     
    Last edited: Mar 11, 2015
  5. Mar 12, 2015 #4
    Its good to know how garbage collection works with deleting some things. If I make three variables a,b,c and set a=myobject(), b=a and c=a, then all three variables will be pointers to the same instance of myobject in memory. Garbage collection removes objects in memory nothing is pointing to. That means deleting variable a deletes the object if its the only thing pointing to it, but in the case above its not, b and c also point to it, so by deleting a you can still access the object through b and c.
     
  6. Mar 17, 2015 #5
    Yes thanks Mark44, it's *i=10; :-p
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: PHP: Deleted but still remains
  1. PHP Help ? (Replies: 16)

  2. Php or c++ ? (Replies: 40)

  3. PHP - limiting output (Replies: 7)

Loading...