Why Does the Value Persist After Deletion in This PHP Code?

  • Context: PHP 
  • Thread starter Thread starter Silicon Waffle
  • Start date Start date
  • Tags Tags
    deleted Php
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
Silicon Waffle
Messages
160
Reaction score
202
C:
using namespace std;
class A
{
   int i;
public:
   A();
   void Set(int& i){this->i=i;}
   void Print(){count<<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:
Physics news on Phys.org
Soo sorry I post in the wrong forum. It should be the Programming forums up there. :nb)
Thank you any way:bow:
 
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:
  • Like
Likes   Reactions: Silicon Waffle
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.
 
  • Like
Likes   Reactions: Silicon Waffle
Mark44 said:
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.
Yes thanks Mark44, it's *i=10; :-p