Jump to content

  • Log In with Google      Sign In   
  • Create Account


C++: Why to use pointers?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
29 replies to this topic

#1 BeatOne   Members   -  Reputation: 122

Like
0Likes
Like

Posted 26 December 2005 - 03:47 AM

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? :)

Sponsor:

#2 uncle albert   Members   -  Reputation: 122

Like
0Likes
Like

Posted 26 December 2005 - 03:51 AM

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

#3 ToohrVyk   Members   -  Reputation: 1591

Like
0Likes
Like

Posted 26 December 2005 - 03:56 AM

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 Anonymous Poster_Anonymous Poster_*   Guests   -  Reputation:

0Likes

Posted 26 December 2005 - 03:58 AM

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++

#5 T1Oracle   Members   -  Reputation: 100

Like
0Likes
Like

Posted 26 December 2005 - 03:58 AM

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]
Programming since 1995.

#6 rip-off   Moderators   -  Reputation: 7958

Like
0Likes
Like

Posted 26 December 2005 - 03:58 AM

if you use any std container, you are indirectly using pointers. same with polymorphism. i find plenty of uses for pointers...

#7 BeatOne   Members   -  Reputation: 122

Like
0Likes
Like

Posted 26 December 2005 - 03:59 AM

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?

#8 mikeman   Members   -  Reputation: 2182

Like
0Likes
Like

Posted 26 December 2005 - 04:00 AM

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;
}
}
};






#9 BeatOne   Members   -  Reputation: 122

Like
0Likes
Like

Posted 26 December 2005 - 04:01 AM

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..?

#10 BeatOne   Members   -  Reputation: 122

Like
0Likes
Like

Posted 26 December 2005 - 04:03 AM

mikeman: Thanks, that example was good. :)

#11 T1Oracle   Members   -  Reputation: 100

Like
0Likes
Like

Posted 26 December 2005 - 04:14 AM

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.

#12 uncle albert   Members   -  Reputation: 122

Like
0Likes
Like

Posted 26 December 2005 - 04:29 AM

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.

#13 Anonymous Poster_Anonymous Poster_*   Guests   -  Reputation:

0Likes

Posted 26 December 2005 - 11:48 PM

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.

#14 ToohrVyk   Members   -  Reputation: 1591

Like
0Likes
Like

Posted 27 December 2005 - 12:00 AM

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.

#15 Grain   Members   -  Reputation: 429

Like
0Likes
Like

Posted 27 December 2005 - 02:20 AM

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.



#16 Iftah   Members   -  Reputation: 409

Like
0Likes
Like

Posted 27 December 2005 - 02:29 AM

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?


#17 PaulCesar   Members   -  Reputation: 524

Like
0Likes
Like

Posted 27 December 2005 - 02:41 AM

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.

#18 Guimo   Members   -  Reputation: 463

Like
0Likes
Like

Posted 27 December 2005 - 02:43 AM

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


#19 jpab   Members   -  Reputation: 881

Like
0Likes
Like

Posted 27 December 2005 - 02:46 AM

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

#20 moeron   Members   -  Reputation: 326

Like
0Likes
Like

Posted 27 December 2005 - 02:48 AM

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





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS