In most cases, languages will not allow manipulations of references to primitives. Eg.:
var a = 0;
var b = a; // value is copied
b++; // b now represents a new value as this is really b = b + 1; so a != b
While manipulation of non-primitives will cause a (sometimes destructive) state manipulation which is reflected in all variables(using JS):
var a = [];
var b = a; // b is now a reference to the value stored in a.
a.push(1); // b[0] is now 1 -- b and a are pointing to the same thing.
This makes perfect sense. I can completely understand why things like String.replace will return a value instead of performing a state manipulation.
I was wondering, though, if there aren't any languages开发者_如何学编程 which allow primitives to have state manipulations. Eg.:
var a = 0;
var b = a; // b references a
b++; // b and a are now = 1.
I am aware of the pointer in the more low level languages, and that almost does what I'm talking about, but I get the feeling that it is only re-assigning the value and not actually updating a reference.
I also know about PHP references but since PHP does not allow things like this:
$str = "abcd";
$st[0] = "q"; // this causes an error.
Also, when concatenating a number of Strings in PHP, a cycle of $str .= 'var'
is purported to create new strings each iteration.
Perhaps I'm crazy for even wondering this, but with the increase in prevalence of object models as backgrounds for variables, it seems that this might actually exist (it seems insanely complicated in some ways, especially if you allowed for an int
object being manipulated, but it seems like such a syntax would be a good source of learning).
Contrary to what you seem to assume, this is neither a new idea nor obscure. Lower-level languages don't bother to enforce immutablity of any type (after all, ++i
wouldn't exist or be wasteful otherwise - and the hardware doesn't have constant registers either, right?), but they also will prefer value types (i.e. a = b
copies the value, not silently gives out a reference to the same value), so you have to get your hands dirty and tell it to refer to the same value twice, e.g. by using pointers. In C:
int x = 0;
int *p = &x;
*p = 1;
/* x == 1 */
Similarily, C++ has equally-powerful pointers and also references, which for these purposes work like pointers that are implicitly dereferenced (and can't be changed to point to anything else, and can't be NULL):
int x = 0;
int &y = x;
y = 1;
// x == 1
In either case, it simply didn't occur to anyone to make the primitive types immutable (why should they? Von Neumann machines are all about changing state, after all), pointers lose much of their value if you can't change the value pointed to, and disallowing pointers to certain mutable types would be a pointless and severe restriction.
精彩评论