What is the real difference between Pointers and References?

后端 未结 22 2836
南方客
南方客 2020-12-01 04:33

AKA - What\'s this obsession with pointers?

Having only really used modern, object oriented languages like ActionScript, Java and C#, I don\'t really understand the

22条回答
  •  日久生厌
    2020-12-01 05:01

    I'm currently waist-deep in designing some high level enterprise software in which chunks of data (stored in an SQL database, in this case) are referenced by 1 or more other entities. If a chunk of data remains when no more entities reference it, we're wasting storage. If a reference points so data that's not present, that's a big problem too.

    There's a strong analogy to be made between our issues, and those of memory management in a language that uses pointers. It's tremendously useful to be able to talk to my colleagues in terms of that analogy. Not deleting unreferenced data is a "memory leak". A reference that goes nowhere is a "dangling pointer". We can choose explicit "frees", or we can implement "garbage collection" using "reference counting".

    So here, understanding low-level memory management is helping design high-level applications.

    In Java you're using pointers all the time. Most variables are pointers to objects - which is why:

    StringBuffer x = new StringBuffer("Hello");
    StringBuffer y = x;
    x.append(" boys");
    System.out.println(y);
    

    ... prints "Hello boys" and not "Hello".

    The only difference in C is that it's common to add and subtract from pointers - and if you get the logic wrong you can end up messing with data you shouldn't be touching.

提交回复
热议问题