-
pointers--when to use them
I am a self-taught c++ (beginner?) I have been programming for a couple of months.
I have seen, in tutorials and the such, many uses of pointers. I understand basically what they do, etc. but do you really NEED them?
Can someone give me examples of cases in which pointers are much preferred to any other type of variable access? As far as I can tell, you might as well just use the variable names.
Also, I have seen code like this:
Why is the * used?
Thanks
-
Re: pointers--when to use them
Primarily when you want the object you're creating to exist outside of the scope where it was created and to take advantage of polymorphism.
-
Re: pointers--when to use them
This:
int my_int;
Declares an integer, called my_int.
This:
int * my_int;
Declares a pointer to an integer, called my_int. The * in this context indicates the type created will be a pointer to the type expression that precedes the *.
Frankly, pointers are often avoidable as raw pointers in modern C++.
However, the reason they're in the language is the fact that C, the root of C++, was originally implemented to be a kind of assembler, working very close to the level of the underlying CPU, and for that machine, pointers are a fact of it's operation. Languages that don't have pointers, like Java, aren't able to work at that level. Sometimes that's a benefit.
In the beginning phases of study you can just about ignore the pointer.
If you're going to handle images, audio, video or other forms of data like them, you're dealing with raw collections of data held in arrays. You can perform that work entirely in containers, and languages without pointers use analogous containers to operate with that data. In C++, however, you can achieve certain levels of performance that approaches the fastest that the underlying hardware can perform precisely because of constructs that work closely at the CPU's level, and in the case of image, audio and video data, that means pointers.
Another context, already pointed out, where pointers are important is in polymorphism. Java handles this through it's implementation as a reference, but in C++ we can use something called smart pointers to do something very similar. Still, the nature of polymorphic objects is that the type of an object may be more than at first is visible.
Say I have an object B, derived from A. If a function required an A, but I've created a B which has more functionality, it can still operate as an A. If the function took a COPY of an a, as in:
void function( A );
B myb;
Then:
function( myb );
would imply a copy is passed to function. But what about the part of the object that is a B? It can get lopped off.
If I pass a reference instead:
void function( A & );
then
function( myb );
would not pass a copy, is passes a reference - which is implemented, under the hood, as a pointer.
I could also pass a pointer:
void function( A * );
function( &myb );
This time I have to pass the address of myb, but still it's not a copy - and the function gets use of my entire object, including virtual functions in B that may offer unique behavior.
There's a lot more to it than just that, but this is one example.
-
Re: pointers--when to use them
Quote:
Languages that don't have pointers, like Java, aren't able to work at that level.
It should be noted that from a certain point of view, all non-primitive objects in Java are referred to via pointers. They shouldn't be all that foreign to a Java programmer once they get over the fear of something different.
supahamster, if you have 4 or 10 or 15 objects you need to manage, you can get away with individual variable names for each. If you have a thousand objects, you can't.
One common way of dealing with that many is to throw them in an array. That works, but it has limitations. Fancier data structures may be more applicable. But no matter whether you use an array or something else....you're now referring to 1000 objects in your code with a single variable name.
Obviously there's no magic about it. That container, whatever it is, simply has a way to refer to all of the various objects internally. Not by individual names----same problem----but via a pointer or series of pointers which are arranged to form the data structure.
Read up on linked lists as a good example. Or simply realize that the name of an array is a pointer to the start of that array.
-
Re: pointers--when to use them
Quote:
Can someone give me examples of cases in which pointers are much preferred to any other type of variable access? As far as I can tell, you might as well just use the variable names.
The main reasons I can think of offhand:
A. You need to create an object that can last beyond the local scope.
B. You need to create a dynamic number of something - you don't know the number until the program is actually running*.
C. You want to use polymorphism, which essentially requires the use of pointers.
* You can -and should- make use of things like std::vector in those situations. Ultimately, though, you're still making use of the capabilities of pointers, you just have vector doing all the dirty work for you.
-
Re: pointers--when to use them
Quote:
Originally Posted by
supahamster
I have seen, in tutorials and the such, many uses of pointers. I understand basically what they do, etc. but do you really NEED them?
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. Another is parameter passing in functions.
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.
A different question is whether pointers must be an explicit feature of a programming language? Not necessarily. In C++ it is but in Java it is not.
-
Re: pointers--when to use them
Try this - http://learningcppisfun.blogspot.com...-function.html
It does not cover cross-language viewpoints but just scoped to C++ use of pointers and references - their step brothers - who people think that they hate each other. :)
Pointer is just a way to implement a concept - which is "address of an object". How that concept gets implemented in a language depends on what things were considered during the language design. Some have it implemented as references and some using pointers. There may be other ways to implement that concept that I might not be aware of. If you ask for advantages of reference way of doing it as compared to pointers, well, references can go bad as well. :)
-
Re: pointers--when to use them
Quote:
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.
Quote:
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.
-
Re: pointers--when to use them
In addition to NULLability, pointers have one other advantage over references: They can be reassigned.
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
In addition to NULLability, pointers have one other advantage over references: They can be reassigned.
Not to mention pointer arithmetic :D
-
Re: pointers--when to use them
Quote:
Originally Posted by exterminator
In C# or Java, the nullable-ness of references overcomes that.
I regard references in C# and Java as pointers without pointer syntax. If null C++ references existed, then one benefit of C++ references over pointers would be gone... and references would become pointers with a different syntax. (Okay, and without pointer arithmetic, which admittedly is one difference between C# and Java references and pointers other than syntax.)
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
In addition to NULLability, pointers have one other advantage over references: They can be reassigned.
Point taken, but if a reference could be NULL at one time and not NULL at one time, I thought that it would be implicit that references are reassignable. Anyways, that is what I had in mind when I was comparing with Java/C# references and it is just a hypothetical case of talking of changing the way C++ references work, which would be a non-trivial task, I feel.
-
Re: pointers--when to use them
Quote:
Originally Posted by
HighCommander4
Not to mention pointer arithmetic :D
Ok. :)
Do you mean to say that what can be achieved in C++ with pointer arithematic cannot be achieved in say C#/Java where you don't have pointers and hence pointer arithematic? Any example?
-
Re: pointers--when to use them
Quote:
Originally Posted by
laserlight
I regard references in C# and Java as pointers without pointer syntax. If null C++ references existed, then one benefit of C++ references over pointers would be gone... and references would become pointers with a different syntax. (Okay, and without pointer arithmetic, which admittedly is one difference between C# and Java references and pointers other than syntax.)
Pointer arithematic only seems a necessity because of the way pointers are modelled in C or C++. When you talk of objectives being achieved with that in C++, are you saying something similar can't be done in say Java or C#? I don't think so. There might be a different way to do it, but surely it would be possible to do it. If you think no, then it would be nice to have an example.
-
Re: pointers--when to use them
Quote:
Originally Posted by exterminator
When you talk of objectives being achieved with that in C++, are you saying something similar can't be done in say Java or C#? I don't think so.
I did not talk about objectives. Rather, I talked about pointer arithmetic. You simply cannot "increment" or "advance" a reference, or "subtract" references in C# and Java (and C++). Just because you can say, use iterators instead does not change that fact with respect to my assertion that references in C# and Java are pointers without pointer syntax. What I have in mind is that effect where you can pass an object reference to a function, and assigning to that object reference would not change the object reference in the caller since the reference itself is passed by value.
-
Re: pointers--when to use them
Quote:
Originally Posted by
exterminator
Quote:
Originally Posted by HighCommander4
Quote:
Originally Posted by Lindley
In addition to NULLability, pointers have one other advantage over references: They can be reassigned.
Not to mention pointer arithmetic
Ok. :)
Do you mean to say that what can be achieved in C++ with pointer arithematic cannot be achieved in say C#/Java where you don't have pointers and hence pointer arithematic?
No, I mean to say that what can be achieved in C++ with pointer arithmetic cannot be achieved in C++ with references. Clearly Lindley was talking about C++ references, since Java/C# references can be reassigned.
-
Re: pointers--when to use them
Quote:
Originally Posted by
laserlight
I did not talk about objectives. Rather, I talked about pointer arithmetic. You simply cannot "increment" or "advance" a reference, or "subtract" references in C# and Java.
Well, so did I but I got dragged into it. :)
I only mentioned 2 ways to model something. There could be a disjoint set of baggage that comes along with those different models. So, comparing them was not my point. Ultimately, what matters is how you are using something to achieve the application requirements. It might have been an understatement on my part to say that there was only one difference but that was used as an example to illustrate a more general point I was putting up.
Trying to modify the way C++ references work in C++ in any way is not a trivial task to do, it would need lots of thoughts and is a hypothetical case. I was just merely stating that pointers or references are just different ways to implement a concept: "address of an object". There might be nitty-gritties involved that are peculiar to one particular implementation. If both implementations were the same, why would you need 2 different implementations? That would be an overhead, we could easily work without.
But if you ask me what is the most important different between a reference and a pointer in C++: I still maintain the view that NULLability is the one. But that is just my view and people may differ. :)
-
Re: pointers--when to use them
Quote:
Originally Posted by exterminator
But if you ask me what is the most important different between a reference and a pointer in C++: I still maintain the view that NULLability is the one.
Yes, I believe many of us here agree with you since it is one of the most often cited reasons for choosing a reference parameter over a pointer parameter when a newbie asks about how to make such a decision.
-
Re: pointers--when to use them
Quote:
Originally Posted by
HighCommander4
No, I mean to say that what can be achieved in C++ with pointer arithmetic cannot be achieved in C++ with references. Clearly Lindley was talking about C++ references, since Java/C# references can be reassigned.
Yeah, alright. Sure. I already accepted it would have been an understatement on my part if I sounded like : nullability was the only different between C++ pointers and C++ references. :)
-
Re: pointers--when to use them
Thanks everyone, this has been very useful. Originally, I thought that simply using the variable name again would suffice but I had been making 2 assumptions:
1. small-scale programs vs. 100+ object programs
2. I hadn't realized the benefits of pointer arithemtic
Thanks again
-
Re: pointers--when to use them
Quote:
Originally Posted by
exterminator
int& ref = *(new int(0));
Hopeless Nerd: Look at me, look at me, I'm a genius,
int& ref = *(new int(0));
Team Leader: Use a pointer variable for heavens sake, or I'll assign you to the Java team where you cannot **** up.
-
Re: pointers--when to use them
That particular example is probably a bad idea.
However, good C++ programmers will always prefer references over pointers when all else is equal, since they're, indeed, harder to **** up.
That's what it always comes down to at the end of the day. Write your code in whatever style makes it hardest to do something stupid, and easiest to see at a glance what's going on.
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
That particular example is probably a bad idea.
I'd call it a pretty terrible idea TBH:
Code:
struct Foo
{
int& a;
int& b;
Foo(int& a_)
: a(a_), b(*(new int(0)))
{
}
~Foo( )
{
delete &a; // oopsie
delete &b;
}
};
-
Re: pointers--when to use them
No argument here.
There's rarely any good reason to do anything with the result of a new except assign it to a smart pointer of some type immediately.
-
Re: pointers--when to use them
The example was just to show that the generalized statement made as in:
Quote:
Originally Posted by nuzzle
- to refer to memory allocated on the heap.
was not completely true. This was just to show that a reference could be linked to an object on the heap until anytime upto the end of the object's lifetime. Return of new was not what the example was just limited to illustrate. Plus I think you missed the rest of the statements I made there in where I mentioned about possibility of null references and the way you could have nothrow version of new be able to cope up with the syntax and hence leading to a possibility that new could well have been returning a reference. But I guess if you can skip all that context, it might as well sound like a Hopeless Nerd. Thanks for the comment.
-
Re: pointers--when to use them
It's my view that it's perfectly permissible to refer to a heap object by reference anywhere except at the level of allocation/deallocation (which should, of course, be the same). That level knows it's heap-allocated, and should carry it in a pointer and deal with it as such. Every other level should make no assumptions about whether it's heap-allocated or not.....except, possibly, when referring to the object via an abstract base class. In that case it's permissible to use either a pointer or reference, whichever is more convenient for the particular usage.
-
Re: pointers--when to use them
Quote:
Originally Posted by
exterminator
The example was just to show that the generalized statement made as in:
was not completely true. This was just to show that a reference could be linked to an object on the heap until anytime upto the end of the object's lifetime. Return of new was not what the example was just limited to illustrate. Plus I think you missed the rest of the statements I made there in where I mentioned about possibility of null references and the way you could have nothrow version of new be able to cope up with the syntax and hence leading to a possibility that new could well have been returning a reference. But I guess if you can skip all that context, it might as well sound like a Hopeless Nerd. Thanks for the comment.
OP: Are pointers really necessary in C++?
Exterminator: No, no, no, you can use references instead.
OP: But are references really necessary then?
Exterminator: No, no, no, you can use pointers instead.
-
Re: pointers--when to use them
Well, that's more or less true. Each has specific niches where it's slightly more applicable, but the two are pretty interchangeable, all things considered.
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
Well, that's more or less true. Each has specific niches where it's slightly more applicable, but the two are pretty interchangeable, all things considered.
Except, of course, for pointer arithmetic. Sorry to be so obnoxious ;)
-
Re: pointers--when to use them
Quote:
Originally Posted by
exterminator
The example was just to show that the generalized statement made as in:
was not completely true. This was just to show that a reference could be linked to an object on the heap until anytime upto the end of the object's lifetime. Return of new was not what the example was just limited to illustrate. Plus I think you missed the rest of the statements I made there in where I mentioned about possibility of null references and the way you could have nothrow version of new be able to cope up with the syntax and hence leading to a possibility that new could well have been returning a reference. But I guess if you can skip all that context, it might as well sound like a Hopeless Nerd. Thanks for the comment.
So you don't think that one of the most important uses of pointers in C++ is to point to allocated memory on the heap?
Then why is every known way to get at memory on the heap returning a pointer?
-
Re: pointers--when to use them
Quote:
Originally Posted by
exterminator
The example was just to show that the generalized statement made as in:
was not completely true. This was just to show that a reference could be linked to an object on the heap until anytime upto the end of the object's lifetime. Return of new was not what the example was just limited to illustrate. Plus I think you missed the rest of the statements I made there in where I mentioned about possibility of null references and the way you could have nothrow version of new be able to cope up with the syntax and hence leading to a possibility that new could well have been returning a reference. But I guess if you can skip all that context, it might as well sound like a Hopeless Nerd. Thanks for the comment.
To put in a personal reflection.
My reply in #6 was an attempt to give the broad view, to see the forrest and not the individual trees. And I think it was very good actually.
Then in comes you. The nerd, incapable of taking the broader view of things.
I tell you this. Do you have a better overview than I gave in my reply #6? Then post it! On the other hand if you want to discuss "the individual trees" then put in your claims and I'll reply. And you'll be surprised, the topic of pointers in C++ is wider than you've ever imagined.
-
Re: pointers--when to use them
Quote:
Originally Posted by
nuzzle
So you don't think that one of the most important uses of pointers in C++ is to point to allocated memory on the heap?
Then why is every known way to get at memory on the heap returning a pointer?
Well, putting aside the fact that this is an artifact left over from C for better or for worse, the vast majority of code should not *care* whether the objects it's operating on live on the stack or the heap.
So the only place the origin of the object matters is on the level where it is created. On that level (and anywhere 'ownership' of the object may have meaning), sure, putting heap objects into a smart pointer makes much more sense than putting them into a reference.
Everywhere else, the driving concerns should be
1) Is NULL a valid value for the thing or not
2) Which produces cleaner-looking code.
There are other considerations, but those are the ones most often directly relevant.
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
Well, putting aside the fact that this is an artifact left over from C for better or for worse, the vast majority of code should not *care* whether the objects it's operating on live on the stack or the heap.
So the only place the origin of the object matters is on the level where it is created. On that level (and anywhere 'ownership' of the object may have meaning), sure, putting heap objects into a smart pointer makes much more sense than putting them into a reference.
Everywhere else, the driving concerns should be
1) Is NULL a valid value for the thing or not
2) Which produces cleaner-looking code.
There are other considerations, but those are the ones most often directly relevant.
What did you say and how does it contribute to this thread?
-
Re: pointers--when to use them
Hey, you're the one pretending you know better than everyone. One bad example was posted, true, but pointing that out was all that was necessary.
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
Hey, you're the one throwing names around and pretending you know better than everyone. I'm just here to help.
There's more than enough nonsense posted around these parts from time to time without jumping on the backs of those who are more or less right, that's all.
So you think you're right without saying?
I don't buy that.
You have to promote your arguments like anybody else.
-
Re: pointers--when to use them
Oh, hell no. I'm wrong all the time. I welcome such instances, since it gives me an opportunity to learn some better techniques and strategies.
Over-use of pointers was one of the ways I used to be wrong. Since I started using references more (together with a heavier emphasis on STL constructs), my code has become much safer, cleaner, and more readable. It's still evolving, of course. There are always opportunities for style improvement.
My point above was simply: Using a (smart) pointer to own an object on the heap is wise. But there's absolutely no reason to prefer pointers over references just because the object in question came from the heap, so long as the pointer (or reference) in question isn't expected to represent ownership of the object.
-
Re: pointers--when to use them
Quote:
Originally Posted by
Lindley
Oh, hell no. I'm wrong all the time. I welcome such instances, since it gives me an opportunity to learn some better techniques and strategies.
Over-use of pointers was one of the ways I used to be wrong. Since I started using references more (together with a heavier emphasis on STL constructs), my code has become much safer, cleaner, and more readable. It's still evolving, of course. There are always opportunities for style improvement.
My point above was simply: Using a (smart) pointer to own an object on the heap is wise. But there's absolutely no reason to prefer pointers over references just because the object in question came from the heap, so long as the pointer (or reference) in question isn't expected to represent ownership of the object.
I know. You think you're the greatest but that's not what we're discussing.
Look at my reply #6. Then tell me what you think.
-
Re: pointers--when to use them
Okay.
Quote:
There are many algorithms, data structures and language mechanisms you simply cannot implement efficiently without the use of pointers.
Assuming you're working from scratch, yes. If you leverage the STL you can create lots of data structures and run lots of algorithms without resorting to pointers. Of course, they probably use pointers internally, but from my view that's beside the point---you should never care about details past an interface when coding.
Quote:
One important example is recursive data structures such as lists and trees.
I would say those are the poster child for pointer usefulness, assuming again you're talking about starting out at the C level and coding from there.
Quote:
Another is parameter passing in functions.
I'd actually say that using a pointer for an out parameter without a good reason (and there are a few) is actually a sign of someone too steeped in the C mindset. A good C++ coder should choose references or pointers for parameter passing depending on the rules I posted in #32, barring a good argument otherwise.
Quote:
The two most important uses of pointers are,
- to avoid extensive shuffling of data back and forth in memory, and
Certainly when dealing with heavyweight objects, moving pointers to them is a lot better than moving the entire object. No argument there. There are various ways this could be done without explicitly requiring the use of pointers, such as shuffling an index array, but that's largely a matter of semantics.
Quote:
- to refer to memory allocated on the heap.
That's what the central issue is, isn't it? My argument is that yes, pointers are better for referring to something on the heap.....when you know where it is. And the amount of code that cares about where the object is should be as small as possible. Again, details past an interface shouldn't matter, so wrap up the messy details in as tight an interface as possible so you can present a clean face to the world.
exterminator's point was an extreme example of that---too extreme. But what he was getting at is correct; that you can (and should!) treat heap-allocated and stack-allocated objects as identically as possible whenever you can; and that includes referring to them via references sometimes.
Quote:
A different question is whether pointers must be an explicit feature of a programming language? Not necessarily. In C++ it is but in Java it is not.
Personally, I feel that a difference which makes no difference is no difference. Java may not have something called a pointer exactly, but their references do the same exact things for the most part.
Quote:
I know. You think you're the greatest but that's not what we're discussing.
I think I'm still exploring the solution space with a high temperature. I haven't gotten so far along in the simulated annealing process to suspect myself of nearing a global optimum yet.