Sign in to follow this  
jagguy

pointers

Recommended Posts

in game programming is there a standard for use of pointers eg in vc++6 I see a lot of pass by reference in code listings...I like this better i see some pointers to classes.......why would you need such a thing i can understand using pass by reference in functions, member functions but I am hazy on the need for pointers

Share this post


Link to post
Share on other sites
References are just pointers with a bit more safety in exchange for less flexibility.

A reference must always be initialized, which is good in that you know it's always pointing to something valid, but bad in that it cannot be used for optional values (like a parent pointer being NULL to mean no parent). Because of this, references are usually consigned to function arguments and local variables. You also cannot re-assign a reference (if you try to re-assign it, you just end up modifying what it refers to, which makes for some fun debugging).

Pointers suffer no such restrictions, but by that same token are more dangerous. You can modify where a pointer points to as well as what it points to. It can point to something valid, or something invalid. It can be unitialized (but shouldn't be).

Share this post


Link to post
Share on other sites
so you could get away with a OO c++ program with just references.

in what case would you need to use a pointers though, you still see pointers everywhere?

Share this post


Link to post
Share on other sites
If you want to dynamically allocate memory then you need to use pointers e.g.



class Dummy
{
private:
int* values;
public:
Dummy(int n)
{
values = new int[n];
}
virtual ~Dummy()
{
if(values)
delete[] values;
}
};




Like foofightr says references are less flexible, you can delete them, although this isn't a bad thing, I tend to use references for passing and returning values and pointers for dynamic memory allocation.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Pointers are better choice when you have to change its value. References are initialized when they are created, and you can't change the variable it references afterwards.

Here's a code on using pointers for a changing variable it points:

float f1, f2;
float* pCurrentVal;

void Print()
{
cout << (*pCurrentVal) << endl;
}

int main()
{
f1 = 120.0f;
f2 = 56.0f;

pCurrentVal = &f1:
Print();
pCurrentVal = &f2;
Print();

return 0;
}

Share this post


Link to post
Share on other sites
Quote:
Original post by jagguy
in game programming is there a standard for use of pointers eg in vc++6 I see a lot of pass by reference in code listings...I like this better

i see some pointers to classes.......why would you need such a thing
i can understand using pass by reference in functions, member functions but I am hazy on the need for pointers


References and pointers pretty much are the same thing under the hood.

Advantages of references:

1) You can expect it will be valid to use
2) object.fnord syntax instead of object->fnord syntax

Advantages of pointers:

1) They don't necessairly have to actually be valid
2) (re)assignable instead of contstruct-only

Pointers are SOMEWHAT of an aftereffect from C. No, let me rephrase that: the common use of pointers as function arguments is somehwat an aftereffect from C, as that was the only method of passing arguments to be modified in that language. Reasons for continuing this trend include:

1) Force of habit
2) Uniformity (with other functions which may need pointer-type syntax)

That said, I use references a lot, more than pointers in my function arguments.

Share this post


Link to post
Share on other sites
a lot of good replies here I must say so thanks for that.

i prefer references for passing as argument to functions.

with the dynamic allocated memory, i am a little confused on that because you could use a temporary variable couldnt you....i am a bit rusty on that 1

I see you can have a pointer to a function or member function which you cant do with a reference (I dont know why you would need to), and eg directX functions require pointers as arguments

I need to do some programming to get a better grasp of it, i guess

Share this post


Link to post
Share on other sites
If you want to allocate a certain number of objects based on a value which can only be determined at run-time, for example if it is read from a file or entered by the user then you have to use dynamic allocation.

Share this post


Link to post
Share on other sites
Quote:
Original post by jagguy
a lot of good replies here I must say so thanks for that.

i prefer references for passing as argument to functions.


Again, completely understandable (IMHO) since this is the same as with myself.

Quote:
with the dynamic allocated memory, i am a little confused on that because you could use a temporary variable couldnt you....i am a bit rusty on that 1


Let me (attempt to) address this bit.

First off, I'll assume we can agree that you NEED to use pointers in order to manage memory using new/delete (or their array equivilants, new[]/delete[]) as that is what they return. Why are they useful?

Consider for a moment a unit in a real time strategy game. Temporary variables (as in, temporary by scope, declared in a function and gone once that function ends) are insufficient here, as the lifetime of the unit is much longer than the execution of one function (unless the base that produced it is getting obliterated by a thousand artilery shells - but that's another issue :P).

On the other hand, global variables are insufficient here, as there's going to be more than 1 unit, and we don't know the upper limit of units (to keep our engine flexible). Thus, we can't just do: "game_unit all_units[1000];" or we'll have problems when we reach unit 1001.

That said, there are times we can let other people take care of all the "nasty" pointers... by using the STL for example, the above could become:

std::deque< game_unit > all_units;

which could then be resized as needed.

Quote:
I see you can have a pointer to a function or member function which you cant do with a reference (I dont know why you would need to), and eg directX functions require pointers as arguments


Since member functions are dealt with in a somewhat odd manner (as offsets to the class base, which are then called in conjunction with a variable - aka, you provide the "this" argument) making them references is a bit of a crazy idea (IMHO). The closest thing to a member-function reference would be boost::function combined with boost::bind - but a boost::function is reassignable, and isn't callable in some "
"provide_this.*provide_function( provide_argument );" scheme that I'm aware of - it can only keep the finished product (as far as I know, minus the arguments).

Quote:
I need to do some programming to get a better grasp of it, i guess


Another benifit of pointers that I frogot to mention is that they can be accessed like arrays, or incremented. For example:
char * pie = "fnord";

In this example, pie really points to only one character - 'f'. It points to the START of the entire string, "fnord". With basic C-style manipulation you might write your own printstring function:
void printstring( char * string )
{
for ( char * character = string ; *character != '\0' ; ++character )
{
putch( *character );
}
}

Of course, in C++ you should probably be using std::string, and sure, this function could be optimized (by just calling puts for example :P) but it gets the point accross. You're realling accessing the string one character at a time. This is extremely similar to iterators, which are used for accessing STL containers in this manner.

Share this post


Link to post
Share on other sites
This is a common phase in the lives of new programmers. The first question is usually "What the hell is THAT?", followed quickly by "Why would anyone ever need THAT?", where THAT is any new and confusing concept. Eventually, your questions will become "THAT looks different." and "THAT could come in handy!", where THAT is any new and exceptionally clever yet mildly confusing concept.

It is, unfortunatly, a bit of a catch-22. If you had the knowledge to understand why you would want to use pointers, you wouldn't have to ask.

Sure, you can program without them, but theres an awful lot of stuff you can't do without a pointer or reference mechanism. Many people tout Java as an example of a pointer-free language; removing them certainly did not make Java programs any easier to write.

On another note, I don't use dumb pointer variables very much. I may take the address of a variable, usually to pass to an API I didn't write, but if I new it, it goes into a smart pointer immediatly.

Share this post


Link to post
Share on other sites
Quote:
Original post by Deyja
Sure, you can program without them, but theres an awful lot of stuff you can't do without a pointer or reference mechanism. Many people tout Java as an example of a pointer-free language; removing them certainly did not make Java programs any easier to write.


Only if Sun's marketing department and the set of easily impressionable people in IT constitute "many".

... oh wait... [smile]

My point being: realistically, it is not a "pointer-free language"; there is no such thing really. Note "NullPointerException".

What Java *does* do for you is clean up the whole mess of having to specify pointers and references and so forth, by (a) treating arrays like actual objects which can be returned, passed without weird complications etc., and (b) implicitly making object-type variables actually store a pointer, such that when you pass an object, you pass-reference-by-value.

This results in amazingly cleaner looking code because there is no longer a -> vs . dichotomy, and you get rid of all the other *&*&ing syntactical annoyances associated with layers of indirection.

Quote:
On another note, I don't use dumb pointer variables very much. I may take the address of a variable, usually to pass to an API I didn't write, but if I new it, it goes into a smart pointer immediatly.


This may be overkill, but I haven't seen you projects so... (Of course, if it really helps you that much, don't you really wish you were working in a garbage-collected language/environment in the first place?)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Well, why /not/ auto_ptr all your pointers? Saves you work, makes your code easier to follow, and makes exception safety much easier...

Share this post


Link to post
Share on other sites
Quote:
Well, why /not/ auto_ptr all your pointers? Saves you work, makes your code easier to follow, and makes exception safety much easier...


The AP really got the most of it. A memory leak due to an exception being thrown in unacceptable. A memory leak due to anything is unacceptable. However, garbage collection - and psuedo-pointers - can't model everything. I admit I have run into some iffy spots. Just recently, I found myself passing dumb pointers to smart pointers into my scripting language module. :D

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
Well, why /not/ auto_ptr all your pointers? Saves you work, makes your code easier to follow, and makes exception safety much easier...


Storing auto_ptrs in a STL container won't work right, in particular if you were hoping to, you know, actually share the object with someone else. Storing raw pointers can be made to work (although you have to figure out the ownership semantics).

Share this post


Link to post
Share on other sites
I need to have some experience with larger programs first before my questions improve.

I dont understand the need for dynamic memory allocation in a game setting and posted another thread on that. I can see the use for references with passing by Byref

thats a big step so far

Share this post


Link to post
Share on other sites
Quote:
Storing auto_ptrs in a STL container won't work right, in particular if you were hoping to, you know, actually share the object with someone else. Storing raw pointers can be made to work (although you have to figure out the ownership semantics).


That's when you use a reference counted smart pointer or reference linked smart pointer.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this