C++: Why to use pointers?

Started by
28 comments, last by BeanDog 18 years, 3 months ago
Quote:Original post by BeatOne
T1Oracle: Sorry about my bad spelling, I am busy chasing polarbears down the streets.. :)

No seriously, I still don't understand the major advantage using pointers, other than memoryefficient..?

I said that it was faster. The less memory your program has to allocate and deallocate, the less time your computer has to waste doing those CPU time consuming operations. The time costs of that is even greater for larger objects. Most of the time structures and classes should be passed by referrence.
Programming since 1995.
Advertisement
Quote:Original post by mikeman
He's using C++, in which you can pass by reference without using a pointer.
*


Sorry, I kind of regarded "pointer" in this case to mean a variable holding an address, rather than going in to the whole pointers v references thing. I should've been more clear.
i think every time you want to allocate memory dynamically (and manage it), you have to use pointers. i can't think of a bigger program without pointers at all.
and you use them of cause when you want to refer to another object.
lets say you have a ressource managing class and now you want an object to use that ressource. so you implement a pointer to a ressource in the class of that object. you won't keep that ressource in memory twice.

btw every time you use a reference, the compiler internally uses a pointer.
that means every call by reference is some kind of workaround so that you don't have to use the dereference-operator.
Quote:Original post by Anonymous Poster
btw every time you use a reference, the compiler internally uses a pointer.
that means every call by reference is some kind of workaround so that you don't have to use the dereference-operator.


Not really. First of all, the compiler does not internally use a pointer: both pointers and references (which are C++ concepts) are translated to a lower-level implementation, which involves memory addressing machine code in the case of pointers and sometimes in the case of references as well. While the use of pointers (or unary &) forces the compiler to place the variable in memory and manipulate its address, a referenced variable can be placed in a register if its use is local. Consider:

bool a;while(a) { someInlineFunctionRef(a); }while(a) { someInlineFunctionPtr(&a); }


The second loop forces a to be placed in normal memory, so its address can be taken. The first loop does not prevent the compiler from placing a in a register.

Also, in the case of const int & arguments, a compiler would be able to safely pass the integer by value instead of reference (although such behavior might be prevented by the ABI).

References also allow you to pass temporary values by reference instead of by value. Another advantage is that you don't need to check for NULL references.
Quote:Original post by ToohrVyk
In C++, pointers are useful mainly in three situations:


  1. To interface with C code which uses them (strings, pass-by-reference, arrays) and with dynamic memory allocation (operator new and operator delete).

  2. To implement reseatable references (or optional content represented by a NULL) pointer.

  3. For low-level arithmetic operations on memory addresses (computing offsets, moving to offsets, and similar tasks).



Please note that in case 1 pointers serve only as an interface (and should be quickly converted to a more adapted type), and that in case 2, pointers can be replaced by smart pointers. Case 3 should be limited to only a small portion of any application, and not allowed to permeate outside a single, well-encapsulated module.

However, clean C++ code should not use plain pointers for something other than the above. For instance, call-by-reference should be implemented using references, not pointers, except in case 1 above.


4. To use polymorphic classes.

Quote:Original post by mikeman
If your code works fine without pointers, then you don't need them. One out of the many examples where pointers(either raw C++ pointers or STL constructs like smart pointers) have a use is when you want to store a reference to an object. Say you are making an FPS, and you want to be able to "lock" a specific target and kill him when you shoot:

*** Source Snippet Removed ***


thats not a very robust example... what if two players lock on same target?
one player will shoot and kill, the second player will shoot and make the application collapse.

and cant the same be done with references?
How about this one:

If you allocate memory on the heap rather then the stack, you need a pointer to that memory to referance it. Each program has an individual stack, but its size is limited (I believe 4MB, but I could be wrong on that), if you need to address larger amounts of memory, particularly consecutive, you need direct access to the heap.

Memory created on the stack can be rearranged at any time. Now im not really sure how this works in practice, but theoreticaly the pointer to an object created on the heap can move and is nolonger valid outside of a particular function call, on the other hand, a pointer to a location on the heap remains valid untill it is deleted.

If you wish to allocate memory within a function that is transparent from the call stack, it needs to be on the heap.

Im sure there are others, have to think of them. Appologies if im a bit off on any of these things, tired as hell here.
Hi,
a. Create a class about 100 bytes long (very common)
b. Create an array about 10000 elements of that array (very common)
c. Pass the array to a function... will you risk passing 1Mb each call with the appropiate stack allocation or just 4 bytes for a pointer?

Just think that even some languages that claim they are 'pointer free' like Java or C# use pointers. Why do you think there is still a 'new' instruction?

Luck!
Guimo
Quote:Original post by Iftah
thats not a very robust example... what if two players lock on same target?
one player will shoot and kill, the second player will shoot and make the application collapse.

and cant the same be done with references?

Examples are rarely robust, although in fact that example may be perfectly fine - you can't tell, because you don't know what the Die() method does (it may simply set a 'dead' flag, in which case pointers to the object will still be valid).

And no, the same can't be done with references, because references can only be set when they're created; you can't change them to point to another object later.

John B
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.
Quote:Original post by Grain
4. To use polymorphic classes.


You can make use of polymorphism with references as well as pointers. I think ToohrVyk's list covers the main areas where pointers should be used over references.

eg..
class base{	public:		virtual ~base(void){}};class derive : public base{	public:		virtual ~derive(void){}};int main(int,char**){	derive d;	base const &baseRef = d;	return 0;}

Now perhaps if you wanted an array of base then you would want to use the pointers over references, but I think ToohrVyk's number 2 covers that situation (reseatable references)

moe.ron
moe.ron

This topic is closed to new replies.

Advertisement