working with pointers

Duncan Booth duncan.booth at invalid.invalid
Wed Jun 1 12:41:03 CEST 2005


Shane Hathaway wrote:

> 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);
> }
> 
A closer translation would be:

const Integer CONST0(0);
const Integer CONST2(2);

void test()
{
    const Integer *a, *b;
    a = &CONST0;
    b = a;
    b = &CONST2;
}

The constant integers are created in advance, not when you do the 
assignment. Arithmetic may create new Integer objects, but when the result 
is a small integer it simply reuses an existing object.



More information about the Python-list mailing list