Jump to content
  • Advertisement
Sign in to follow this  
Christopher Murray

Question about Pointers and References

This topic is 2487 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Having a bit of confusion.

According to Beginning C++ Through Game Programming, 2nd edition, Pointers are a powerful part of the C++ language and is a reason so many programmers like it, however it then says to never use them and almost always use references. Is that not confusing?

Basically, from the book and from online tutorials I read about pointers, I get how to use them, but I don't get the difference between pointers and references and when to use pointers. They all show how to use them but don't answer the simple question of "why?".

My two questions:
1) What is the difference between using a pointer and using a reference
2) When should I use pointers instead of references

Thanks

Share this post


Link to post
Share on other sites
Advertisement
1. http://www.go4expert.com/forums/showthread.php?t=5492
http://www.parashift.com/c++-faq-lite/references.html
http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c

2. Pointers as they are in C++ by default can be unsafe to use. They are just variables storing memory addresses. It is the responsibility of the developer to allocate the memory space, free it, make sure it is valid when used and so on. I like to see references as a more strict version of pointers that will stop you from making mistakes, however I am still using pointers a lot since i first started with C programming as a personal preference. They can get you into a lot of trouble, but then they are very powerful. I cannot tell you when to use pointers and when references, it is all up to you and depends on what kind of project are you working on.

Share this post


Link to post
Share on other sites

According to Beginning C++ Through Game Programming, 2nd edition, Pointers are a powerful part of the C++ language and is a reason so many programmers like it, however it then says to never use them and almost always use references. Is that not confusing?

It's confusing if they don't give a reason.

Pointers can point to random parts of memory, and can be intentionally manipulated in wierd and interesting ways. The 'danger' is that it can rather easily be set to point to invalid locations in memory and muck up your program while it's running.

Note: By 'danger', I mean your program can crash and stop running or cease working properly but continue running brokenly (which is worse). I do not mean 'danger' as in, "Oh teh noes, your computer is going to self destruct!". It's more risky in your code, and could likely harm your program, but it wont harm your computer. They aren't to be feared, just used with caution.

Basically, from the book and from online tutorials I read about pointers, I get how to use them, but I don't get the difference between pointers and references and when to use pointers. They all show how to use them but don't answer the simple question of "why?".[/quote]

References can't easily point to invalid locations of memory. Once you set a reference, the reference cannot be re-assigned, making it safer to use.

My two questions:
1) What is the difference between using a pointer and using a reference[/quote]
References are set once at creation and continue to point to the same location.
Pointers can be set after creation and can be re-set to a different location later. You can also do 'pointer arithmetic' on pointers, manipulating where they point to.

This makes pointers much more flexible (or 'powerful' as the books said), but also risky in a couple of ways:
1) You can try to use pointers when they haven't yet been set to point to anything. Not good.
2) You can re-assign pointers to something other than what you initially set them to. Not good, if it was by accident.
3) You can manipulate pointers by math to make them point to something else. Not good, if your math was incorrect.

The danger is that your program can seem to work fine, but actually be accidentally be writing over the wrong locations of memory.
By 'memory', I mean the portion of RAM given by the OS to your program... you wont harm other running programs, and you wont harm your harddrive. The danger is isolated to your program itself, running correctly or running incorrectly or crashing.
2) When should I use pointers instead of references[/quote]
When you create dynamic memory (new/delete), use a pointer to point to the new memory.
However, if you are using C++11, you'd be better off using std::shared_ptr or std::unique_ptr, and std::make_shared().

Use references whenever you want to point to something that you don't want to re-assign later. For example, function parameters.
Almost all my functions pass objects by reference. When you need the extra functionality, then switch to pointers.

Pointers are nothing to fear, they just have harder to find errors associated with them. Most 'horror stories' of programmers involve pointers, not because they are dangerous or unstable in themselves, but just because they don't protect you (the programmer) from doing dangerous things with them.

Share this post


Link to post
Share on other sites
1. a reference cannot be null and cannot be reassigned (Making it fairly difficult to mess them up) (Pointers can be null and can be reassigned and you can also perform arithmetics on them)

2. You should use pointers instead of references when and only when you need to be able to set them to null, reassign them or use pointer arithmetics. (if you only need the null part you should use a const pointer). (Reading up on const correctness is a good idea as it makes your code more robust aswell). (If you are allocating memory on the heap then you need a pointer)

Also, the latest version of the C++ standard adds smart pointers, They are preferable to raw pointers in most cases.

Share this post


Link to post
Share on other sites
Another issue with pointers, besides safety concerns, is that they do not express intent very well. If you see a function that takes a pointer as a parameter, or returns a pointer, you cannot always guess what this means.

  • Is it a pointer to a single object, or an array?
  • Is it allowed to be null?
  • Does the function store a copy of the pointer (disallowing pointers to temporary values as valid arguments)?
  • Does the caller or callee retain ownership of the pointer, or is ownership shared (i.e. who must deallocate it?)
  • ...


    In modern C++, we use language features and standard idioms to express this intent.

    • Functions that take:

      • a single object take a (const) reference or value
      • an "array" usually take iterators or a (const) container reference

      • Functions that have optional arguments can use boost::optional<> (this is one area the standard isn't particularly helpful in - people still use pointers to indicate this)
      • Functions that take objects use:

        • (const) reference or value - the function does not own the caller's object
        • unique_ptr<> - indicating the function expects exclusive ownership
        • shared_ptr<> or weak_ptr<> - indicating the function expects shared ownership

        • Functions that return objects use:

          • values or (const) references - the function retains ownership

          • unique_ptr<> - indicating the function relinquishes ownership to the callee
          • shared_ptr<> or weak_ptr<> - indicating the function shares ownership with the callee

Share this post


Link to post
Share on other sites

Functions that have optional arguments can use boost::optional<> (this is one area the standard isn't particularly helpful in - people still use pointers to indicate this)


Actually the standard does define one and they are default arguments, and you can fix this with class static variables for the defualt parameters in the case of classes and strings.

Share this post


Link to post
Share on other sites
Default arguments and optional arguments are not always the same thing. In some cases though, yes that can be useful.

Share this post


Link to post
Share on other sites
Actually the standard does define one and they are default arguments, and you can fix this with class static variables for the defualt parameters in the case of classes and strings.


A default argument can act as an optional argument only when there exists some object state which can be distinguished from all others which might possibly be passed as the desired argument.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!