• Advertisement
Sign in to follow this  

C++: Why to use pointers?

This topic is 4406 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello there. I sat down the other day wondering, WHY to use pointers. I know how to code with pointers, and my code works the same way without them. Can somebody provide a practical example where it's necissary to use a pointer? :)

Share this post


Link to post
Share on other sites
Advertisement
Obvious example - call by reference and call by value when passing parameters to functions.

Say you've got a hefty object that needs to be accessed by a function. If you use call by value, you're effectively creating a new copy of that object, wasting memory (and even then you'll only be accessing the copied object, and not the original).
By using call by reference, and passing a pointer to the object, not only can you access the original object, but you're saving, potentially, a massive chunk of memory as well. :)

James

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by BeatOne
Hello there. I sat down the other day wondering, WHY to use pointers. I know how to code with pointers, and my code works the same way without them. Can somebody provide a practical example where it's necissary to use a pointer? :)


Functions, classes... anything, really! It's not always a good idea to invoke an object's copy constructor, especially if the object is big... Oh, and also - linked lists ;).

C++

Share this post


Link to post
Share on other sites
Not only does it waste memory, but it wastes CPU time (which can quickly add up) as that extra memory has to be allocated and then deallocated. You want to minimize memory allocations as much as possible as they can take a serious toll on performance.

Also, I understand that you are from Sweden, but: "C++: Why should I use pointers?", "C++: Why would I use pointers?", "C++: Why would you use pointers?", "C++: Why should you use pointers?" would all be improvements. Happy posting [smile]

Share this post


Link to post
Share on other sites
Let me see if I got that right.. Instead of making a new variable(for example), I pass the adress of the original variable, to use that instead?

Share this post


Link to post
Share on other sites
Quote:
Original post by uncle albert
Obvious example - call by reference and call by value when passing parameters to functions.

Say you've got a hefty object that needs to be accessed by a function. If you use call by value, you're effectively creating a new copy of that object, wasting memory (and even then you'll only be accessing the copied object, and not the original).
By using call by reference, and passing a pointer to the object, not only can you access the original object, but you're saving, potentially, a massive chunk of memory as well. :)

James


He's using C++, in which you can pass by reference without using a pointer.

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:


class CPlayer
{
private:
CMonster *target;
public:
CPlayer(){target=NULL;}
void LockTarget(CMonster &monster){target=&monster;}
void Shoot()
{
if (target!=NULL)
{
target->Die();
target=NULL;
}
}
};




Share this post


Link to post
Share on other sites
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..?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
How about this problem (I don't know if someone said it already, i didn't read all the replies):

if you create a function that gives an int back, you can use it like this:
int myint = myfunction(param1, param2, ...);

But what if you want to make a function that need to returns 2 or more value's, you can use pointers like this:
myfunction(&myvar1, &myvar2, &myvar3, ..., myparam1, myparam2, ...);

that way you can also access myvar1, ... an change those values.

Share this post


Link to post
Share on other sites
Quote:
Original post by Spippo
But what if you want to make a function that need to returns 2 or more value's, you can use pointers like this:
myfunction(&myvar1, &myvar2, &myvar3, ..., myparam1, myparam2, ...);


Unless you want your code to be interfaced by C code, you should use references. As I mentioned in my example above, your code forces &myvar1 to be stored in a memory area where it can be addressed, even if it is an inner-loop variable that should have been put in a register instead.

Using references, the compiler is free to decide if he should implement this operation using memory addressing, or by inlining myfunction and having it access the register where the variable is stored.

Share this post


Link to post
Share on other sites
Yes. Using a reference provides more information to the compiler all-around, while also simplifying your work (by letting you not worry about pointer syntax). As a rule, use references where you can, and pointers where you have to. This is basically for the same reason we prefer more specific control structures like if, while, for etc. where possible, and use goto as a last resort (if at all).

As for memory management stuff... use the standard library containers. Please.

Share this post


Link to post
Share on other sites
Quote:
Original post by Iftah
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?


I just wrote a very short example just to demonstrate the use of pointers, I didn't say you can actually implement a multiplayer FPS with that for god's sakes.

And references are not resetable, you initialize like "int &a=b" and that's it. Variable "a" refers to "b" for the rest of its life.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Pointers are not just used for store equivalent data types; another good use of pointer is for storing the direction of a dinamicaly allocated block in memory where you put raw data, like loading a picture, sound, compressed data, etc.


good luck.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement