what was wrong with struct & class in C++?
Kirk McDonald
kirklin.mcdonald at gmail.com
Wed Dec 12 15:44:18 PST 2007
Gregor Richards wrote:
> Martin Hinsch wrote:
>> IMO it makes perfect sense to treat objects as just a more complicated
>> kind of value. Look at the following code:
>>
>> int a=1;
>> a++;
>> int b = a + 10;
>
>
> This code has no function calls. And, if it was all implemented with
> operator overloading, it would be the same whether it had value or
> reference semantics:
>
> Integer a = new Integer(/*magic internal data representing the value 1*/);
> a.opIncrement(); /* no imperative language would implement this as a
> * copy, as then all objects would be immutable */
> Integer b = a.opAdd(new Integer(10)); /* whether the integer is copied
> * or not, a returns a new one, it
> * has no reason to modify its
> * argument */
>
> In other words, this code is irrelevant.
>
I feel strangely compelled to describe Python's behavior in this case,
although I admit I'm not entirely clear what the point is. In Python,
integers are immutable objects.
>>> a = 1 # (1)
>>> a += 1 # (2) Python has no increment/decrement operators
>>> b = a + 10 # (3)
(1) Binds an int object with the value 1 to the name 'a'.
(2) In-place addition is strange in Python. Numbers, being immutable,
cannot actually be modified. Instead, 'a += 1' actually creates a new
int object [see note 1] with the value 2, and binds that object to the
name 'a'. (Thus removing the old reference to the object with the value 1.)
(3) Does exactly what you'd expect: Creates a new int object [see note
1] with the value 12, and binds it to the name 'b'.
Notes:
[1] In fact, it doesn't create a new object: Integer objects below 100
are cached and reused for performance reasons. So here it's /really/
grabbing an object from the cache. This is considered an implementation
detail, however, and is usually best ignored.
--
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org
More information about the Digitalmars-d
mailing list