working with pointers

Shane Hathaway shane at hathawaymix.org
Tue May 31 16:56:59 EDT 2005


Michael wrote:
> sorry, I'm used to working in c++ :-p
> 
> if i do
> a=2
> b=a
> b=0
> then a is still 2!?
> 
> so when do = mean a reference to the same object and when does it mean make
> a copy of the object??

To understand this in C++ terms, you have to treat everything, including
simple integers, as a class instance, and every variable is a reference
(or "smart pointer".)  The literals '0' and '2' produce integer class
instances rather than primitive integers.  Here's a reasonable C++
translation of that code, omitting destruction issues:

class Integer
{
private:
    int value;
public:
    Integer(int v) { value = v; }
    int asInt() { return value; }
}

void test()
{
    Integer *a, *b;
    a = new Integer(2);
    b = a;
    b = new Integer(0);
}

In that light, do you see why a is still 2?

Shane



More information about the Python-list mailing list