|
-
May 28th, 2009, 10:13 AM
#8
Re: pointers--when to use them
 Originally Posted by nuzzle
There are many algorithms, data structures and language mechanisms you simply cannot implement efficiently without the use of pointers. One important example is recursive data structures such as lists and trees.
That is the biggest mental block that I have had for some time in past too and I see that to be a very common one. You ask someone to write a linked list and they will start with a Node structure with a data member and a pointer to next node. 
Pointers are not at all necessary to do that. If you consider the context of my last post above, you can do it using references as well. All you need is a way to refer-to/point-to the next object or to 2 or more nodes in case of tress. Pointers are one way, references are another but well yeah, there has to be a possibility of null references or a way to distinguish that. That is the USP of pointers, I guess, in C++. In C# or Java, the nullable-ness of references overcomes that.
 Originally Posted by nuzzle
The two most important uses of pointers are,
- to avoid extensive shuffling of data back and forth in memory, and
- to refer to memory allocated on the heap.
Not at all necessary, unless I misunderstood you and if you are willing to let go the USP of pointers as I mentioned above. Here is a way to point/refer to an object on the heap:
Code:
int& ref = *(new int(0));
If geniune null references were possible in C++, who knows, you might not have needed to the derefence I did above. new would have returned a reference directly, instead of a pointer. Interesting thought.
Can you help me with my homework assignment?, Before you post!, Use code tags, How to post!, Codeguru technical FAQs, C++ FAQ Lite, Stroustrup: C++ Style and Technique FAQ, Guru of the Week, Comeau C and C++ FAQs, Comeau C++ Templates FAQs, CUJ @ DDJ, Spam threshold
My Blogs : Learning C++ is fun | Abnegator's reflections
Open Threads : C++ Aha! Moments | Nature of work in C++?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|