• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
BeatOne

C++: Why to use pointers?

29 posts in this topic

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

Share this post


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

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

Share this post


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

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]
0

Share this post


Link to post
Share on other sites
if you use any std container, you are indirectly using pointers. same with polymorphism. i find plenty of uses for pointers...
0

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

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




0

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

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

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

Share this post


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

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

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.

0

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

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

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
0

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
0

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
0

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

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.

0

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

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

Share this post


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

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  
Followers 0