Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1411516 Posts in 69380 Topics- by 58436 Members - Latest Member: GlitchyPSI

May 01, 2024, 07:33:17 AM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)Pointer or Reference?
Pages: [1] 2
Print
Author Topic: Pointer or Reference?  (Read 5208 times)
B_ill
Level 0
***


View Profile WWW
« on: July 11, 2010, 03:55:44 PM »

I'm a little fuzzy on the difference between references and pointers. When creating a list of all objects of a certain type, which should I be using and why? What would the declaration of the list look like?

Logged

Game Programmer and Designer
Latest Release: Chemical Cubes for Android and Kindle Fire (iOS coming soon)
Gold Cray
Level 10
*****


Gold Cray


View Profile WWW
« Reply #1 on: July 11, 2010, 04:03:43 PM »

A pointer is a type of variable that contains an address in memory and has to be dereferenced to access that memory. A reference is the location in memory of a normal variable.

The rest sounds like a homework problem, so I won't answer directly, but I will say that you can only use references (in a meaningful manner) on variables that already exist in memory.
« Last Edit: July 11, 2010, 04:13:46 PM by Gold Cray » Logged
Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #2 on: July 11, 2010, 05:00:26 PM »

When creating a list of all objects of a certain type, which should I be using and why? What would the declaration of the list look like?



If by lists, you mean std::list, then the question is moot; references can't be stored in std containers.  References have no size, and are therefore not objects.

The choice of what to store depends on what behavior you want.  If the objects are polymorphic, (they have virtual functions) you probably want to store pointers.  If they aren't polymorphic, storing by value is often the way to go.

Without knowing the exact situation, there is no right answer.
Logged



What would John Carmack do?
B_ill
Level 0
***


View Profile WWW
« Reply #3 on: July 11, 2010, 05:05:29 PM »

If by lists, you mean std::list, then the question is moot; references can't be stored in std containers.  References have no size, and are therefore not objects.

The choice of what to store depends on what behavior you want.  If the objects are polymorphic, (they have virtual functions) you probably want to store pointers.  If they aren't polymorphic, storing by value is often the way to go.

Without knowing the exact situation, there is no right answer.

After spending some more time on the code design, I decided that I do actually want to store them by value, treating these lists as the central repository of critters.


A pointer is a type of variable that contains an address in memory and has to be dereferenced to access that memory. A reference is the location in memory of a normal variable.

The rest sounds like a homework problem, so I won't answer directly, but I will say that you can only use references (in a meaningful manner) on variables that already exist in memory.

Rest assured, this is no homework problem. Most of my work lately has been in C#/XNA, which handles this sort of thing for you.


Logged

Game Programmer and Designer
Latest Release: Chemical Cubes for Android and Kindle Fire (iOS coming soon)
Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #4 on: July 11, 2010, 05:47:23 PM »


After spending some more time on the code design, I decided that I do actually want to store them by value, treating these lists as the central repository of critters.


Beware that this only works if the objects being stored are really all of the same type.  Otherwise you get an effect called "slicing" that is probably not what you want.

Don't try to do this:

Code:
class Tank
{
};

class LaserTank : public Tank
{
};

int main()
{
    std::list<Tank> tank_platoon;
    Tank t1, t2;
    LaserTank lt1, lt2;

    tank_platoon.push_back(t1); // OK!
    tank_platoon.push_back(t2); // OK!
    tank_platoon.push_back(lt1); // DANGER!  Object is sliced into a Tank!
    tank_platton.push_back(lt2); // DANGER!  Object is sliced into a Tank!
}
Logged



What would John Carmack do?
mcc
Level 10
*****


glitch


View Profile WWW
« Reply #5 on: July 11, 2010, 07:40:06 PM »

A rule of thumb, pointers can do everything references can but (see Average Software's post) the reverse is not true. So if you ever find yourself having to ask the question, "which do I use"?, the safe thing is to just use pointers.

When you have more experience the places where references are appropriate will probably start to make more sense.
Logged

My projects:<br />Games: Jumpman Retro-futuristic platforming iJumpman iPhone version Drumcircle PC+smartphone music toy<br />More: RUN HELLO
muku
Level 10
*****


View Profile
« Reply #6 on: July 12, 2010, 12:04:27 AM »

If the objects are polymorphic, (they have virtual functions) you probably want to store pointers.

You also get polymorphic behavior via references though, don't you?


So if you ever find yourself having to ask the question, "which do I use"?, the safe thing is to just use pointers.

That's a bit misleading though since references tend to be a bit safer in the sense of memory safety, i.e. you can't (without some nasty hacks) have null references or uninitialized references, whereas with pointers such things are easily possible.  References also don't allow to shoot yourself in the foot with pointer arithmetic.

But, yeah, the whole thing is a bit fuzzy and it takes quite a bit of experience to figure out which one's right in which situation.
Logged
Klaim
Level 10
*****



View Profile WWW
« Reply #7 on: July 12, 2010, 02:34:44 AM »

I have simpler rules of  thumb with pointers and references that make things easier:

 1. References are nicknames. Forget about how they are implemented, it's not important. Just think of them as nicknames.
 2. Don't use pointers.
 3. If you have to use pointers, because there is no choice, then try using smart pointers instead.
 4. If you can't use smart pointer and have to use pointer, use pointer.


About 2,3 and 4 : the idea is that raw pointers require resource management that can easily become source of bugs, so if you use references and smart pointers instead of raw pointers when you can, you limit the parts of code where there might be pointer management bugs.

One case where you have to use smart pointers (whatever smart pointer appropriate) or raw pointer (if appropriate) is when storing them in STL container.

The reasons is that as references are nicknames, they can't be nicknames of nothing, they really have to be initialized with something to be nickname of.
In the containers, the objects have to be constructible and copyable. Nicknames can't be copied! They are just nicknames! Not objects!

About smart pointers : std::shared_ptr (if you have a recent compiler) is the most common because you dont have to manage it at all. The coming standard will have std::unique_ptr that is excelent to manage ownership in some cases where std::shared_ptr is not "right".

Logged

oahda
Level 10
*****



View Profile
« Reply #8 on: July 12, 2010, 04:44:50 AM »

Entirely avoiding pointers is just a cowardly and bad solution.
If you're never going to use them, why even use C/C++?

Not using pointers for any game that takes more than a a night to make is asking for trouble and awkward solutions.
Pointers that are correctly used are powerful, and if you know how to use them, they don't cause trouble.
Logged

Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #9 on: July 12, 2010, 06:35:45 AM »

A rule of thumb, pointers can do everything references can

No, they can't.  References can bind to temporaries and literal constants, pointers can't do that.

Code:
const int &r = 0; // OK!
const int &r2 = x + y; // OK!

Quote
You also get polymorphic behavior via references though, don't you?

Yes, but you can't store references in containers, which was the main requirement of the original question.

Quote
the idea is that raw pointers require resource management that can easily become source of bugs,

Pointers don't imply that at all.  You can easily pass around pointers to stack or global objects.


And smart pointers in containers are only a solution if all of the objects referenced are dynamically allocated.  I know that at least in my programs, this is rarely the case.
Logged



What would John Carmack do?
LemonScented
Level 7
**



View Profile
« Reply #10 on: July 12, 2010, 10:09:11 AM »

Pointers can be NULL, whereas references can't (at least not without big ugly hacks). As such, you should use references for cases where the reference can be "guaranteed" to point at a valid object, and use pointers in cases where it's possible to not have an object to point to (i.e. when the pointer is NULL). In the case of pointers, it pays to be especially paranoid about the possibility of NULL pointers, and to check that they point at something before every attempt to dereference them.
Logged

Klaim
Level 10
*****



View Profile WWW
« Reply #11 on: July 12, 2010, 04:09:12 PM »

Entirely avoiding pointers is just a cowardly and bad solution.
If you're never going to use them, why even use C/C++?

Not using pointers for any game that takes more than a a night to make is asking for trouble and awkward solutions.
Pointers that are correctly used are powerful, and if you know how to use them, they don't cause trouble.

Who said "entirely avoiding pointers"?

I say "use them when you must, not when you can".

Quote
Pointers don't imply that at all.  You can easily pass around pointers to stack or global objects.

Pointers don't imply anything, as I said they CAN be source of management problems. Avoiding manual management when not necessary is just preventing future coding madness. Sometimes you need it, sometimes not. When you don't need it, why use pointers? You have other cheap solutions that almost totally negate common errors of manipulation of pointers.

Please don't put what I didn't say in my mouth, that's obvious that you can't use C++ without pointers in a big project, but that don't force you to use them every time you have to provide some kind of reference to an object.

By the way, recently I've made a game (SHMUP) prototype with only C++/Boost/SFML and there is almost no raw pointers in my code (only some in one array). That was just not necessary most of the time, and I see the same thing in my dayjobs too.

Use pointers when you MUST.

LemonScented have a good point, and that's exactly where I use them most of the time. In fact in those case I also have other solutions but they often become too overkill compared to pointers.

It's not about not using at all pointers, they are necessary for a lot of manipulations (mostly low layer) but you can avoid them most of the time (in fact in a lot of high layer code)
« Last Edit: July 12, 2010, 04:20:04 PM by Klaim » Logged

Klaim
Level 10
*****



View Profile WWW
« Reply #12 on: July 12, 2010, 04:21:53 PM »

I also forgot to add:
use and abuse of assertions, to check the context but also each time you get a pointer, check for it's state and as LemonScented said, be paranoid.
Logged

Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #13 on: July 12, 2010, 05:01:58 PM »

Quote
Quote
Pointers don't imply that at all.  You can easily pass around pointers to stack or global objects.

Pointers don't imply anything, as I said they CAN be source of management problems.

Please don't put what I didn't say in my mouth

You may want to check what you wrote again, you said that they require resource management.

But enough about that, the general advice, which I also espouse, is to use references when you can, pointers when you must.  I would take this advice one step further and say:

Use values whenever possible, failing that, references, failing that, pointers.
Logged



What would John Carmack do?
deemen
Level 0
***


View Profile WWW
« Reply #14 on: July 12, 2010, 06:04:36 PM »

Take an assembly course, then C and C++ will make way more sense.

As far as I know, references are just pointers with a few syntactic rules to make you less likely to shoot yourself in the foot.
Logged

Project Lead - Programmer @ Crankshaft Games
Current Project: Party of Sin
Average Software
Level 10
*****

Fleeing all W'rkncacnter


View Profile WWW
« Reply #15 on: July 13, 2010, 04:44:47 AM »

As far as I know, references are just pointers with a few syntactic rules to make you less likely to shoot yourself in the foot.

They may be implemented as pointers, but nothing requires this.  Compilers are free to implement references any way they choose.  In fact, the section on references in the language standard doesn't even mention pointers.
Logged



What would John Carmack do?
Klaim
Level 10
*****



View Profile WWW
« Reply #16 on: July 13, 2010, 05:23:42 AM »

Quote
Quote
Pointers don't imply that at all.  You can easily pass around pointers to stack or global objects.

Pointers don't imply anything, as I said they CAN be source of management problems.

Please don't put what I didn't say in my mouth

You may want to check what you wrote again, you said that they require resource management.

Yes but that don't force you to make errors (that was the assertion I replied to)... Anyway you understood what I meant.

Quote
But enough about that, the general advice, which I also espouse, is to use references when you can, pointers when you must.  I would take this advice one step further and say:

Use values whenever possible, failing that, references, failing that, pointers.

Agreed.

Logged

oahda
Level 10
*****



View Profile
« Reply #17 on: July 13, 2010, 05:24:52 AM »

Entirely avoiding pointers is just a cowardly and bad solution.
If you're never going to use them, why even use C/C++?

Not using pointers for any game that takes more than a a night to make is asking for trouble and awkward solutions.
Pointers that are correctly used are powerful, and if you know how to use them, they don't cause trouble.

Who said "entirely avoiding pointers"?

I say "use them when you must, not when you can".

That's no different, because you're never obligated to use them. They're simply very good tools many times.
Logged

Vino
Level 3
***


View Profile
« Reply #18 on: July 13, 2010, 08:06:31 PM »

Why all the pointer hating? I use whatever tool is best for the job. References are neat but since they require an instantiated object and can't hold a NULL value that makes them not useful for a lot of things. Pointers can be dangerous, so the solution to that is to be a thorough programmer, check your pointers for NULL before using them, don't do crazy casting stuff too much, and remember to free them when you're done. If you're so scared of shooting yourself in the foot that you never take the safety off, then you'll never get to use the most powerful part of the rifle and you'll be limited to clubbing people with the stock all day long.

PS: There may not be anything about it in the spec, but from the compiler's perspective there's really no way of implementing references without an internal pointer of some sort, that I can think of anyway.
Logged
muku
Level 10
*****


View Profile
« Reply #19 on: July 14, 2010, 12:02:31 AM »

Pointers can be dangerous, so the solution to that is to be a thorough programmer

Yeah, we know how well that "solution" works. That's why Ubuntu still gives me daily security updates for software which has been around for decades.

I'm with those who say that the use of pointers should be minimized in modern usage of C++.
Logged
Pages: [1] 2
Print
Jump to:  

Theme orange-lt created by panic