c++: when to use pointers?

19,615

Solution 1

If you don't know when you should use pointers just don't use them.

It will become apparent when you need to use them, every situation is different. It is not easy to sum up concisely when they should be used. Do not get into the habit of 'always using pointers for objects', that is certainly bad advice.

Solution 2

Main reasons for using pointers:

  1. control object lifetime;
  2. can't use references (e.g. you want to store something non-copyable in vector);
  3. you should pass pointer to some third party function;
  4. maybe some optimization reasons, but I'm not sure.

Solution 3

It's not clear to me if your question is ptr-to-obj vs stack-based-obj or ptr-to-obj vs reference-to-obj. There are also uses that don't fall into either category.

Regarding vs stack, that seems to already be covered above. Several reasons, most obvious is lifetime of object.

Regarding vs references, always strive to use references, but there are things you can do only with ptrs, for example (there are many uses):

  • walking through elements in an array (e.g., marching over a standard array[])
  • when a called function allocates something & returns it via a ptr

Most importantly, pointers (and references, as opposed to automatic/stack-based & static objects) support polymorphism. A pointer to a base class may actually point to a derived class. This is fundamental to the OO behavior supported in C++.

Solution 4

First off, the question is wrong: the dilemma is not between pointers and stack, but between heap and stack. You can have an object on the stack and pass the pointer to that object. I assume what you are really asking is whether you should declare a pointer to class or an instance of class.

The answer is that it depends on what you want to do with the object. If the object has to exist after the control leaves the function, then you have to use a pointer and create the object on heap. You will do this, for example, when your function has to return the pointer to the created object or add the object to a list that was created before calling your function.

On the other hand, if the objects is local to the function, then it is better to use it on stack. This enables the compiler to call the destructor when the control leaves the function.

Solution 5

You usually have to use pointers in the following scenarios:

  1. You need a collection of objects that belong to different classes (in most cases they will have a common base).

  2. You need a stack-allocated collection of objects so large that it'll likely cause stack overflow.

  3. You need a data structure that can rearrange objects quickly - like a linked list, tree ar similar.

  4. You need some complex logic of lifetime management for your object.

  5. You need a data structure that allows for direct navigation from object to object - like a linked list, tree or any other graph.

Share:
19,615
Jamol
Author by

Jamol

I've been building apps on Android for more than 5 years. My current technology stack consists of Kotlin, Dagger, RxJava/Coroutines and Room. I also have a background in backend development solutions (APIs and admin panels) using PHP and Java. Demo apps demonstrating use of Kotlin, MVVM pattern and some popular libraries: https://github.com/jamolkhon/GithubTestApp (Kotlin, Dagger, Retrofit, Moshi, RxJava) https://github.com/jamolkhon/DemoAccountManagement (Kotlin, Dagger, Retrofit, Moshi, Coroutines, Room) In my free time I like playing Smashing Four.

Updated on June 27, 2022

Comments

  • Jamol
    Jamol about 2 years

    After reading some tutorials I came to the conclusion that one should always use pointers for objects. But I have also seen a few exceptions while reading some QT tutorials (http://zetcode.com/gui/qt4/painting/) where QPaint object is created on the stack. So now I am confused. When should I use pointers?

  • Edison Gustavo Muenz
    Edison Gustavo Muenz over 15 years
    I think the most important point of pointers is controlling the lifetime of objects
  • Pete Kirkham
    Pete Kirkham over 15 years
    int x; int* pointer_to_x = &x; You're repeating the OP's confusion between pointers and heap allocation.
  • Dave Van den Eynde
    Dave Van den Eynde over 15 years
    It's actually a pretty horrible idea.
  • Admin
    Admin over 15 years
    In the case of (1) there is no "perhaps" about the need for a common base. In the case of (2) the only "collection" where this would apply would be a C-style array.
  • David Thornley
    David Thornley over 15 years
    No, passing by const reference instead of value is a good habit to get into. While it uses pointers on the implementation level, it has nothing to do with them conceptually.
  • David Thornley
    David Thornley over 15 years
    +1 for the last, bolded, paragraph, because I can't upvote it more myself.
  • Arnold Spence
    Arnold Spence over 15 years
    Point #2 applies particularly to Qt as most Qt graphics related objects are not copyable.
  • LegendLength
    LegendLength over 15 years
    So both of you: pass objects on the stack, create large arrays on the stack, allocate local variables on the heap, allocate integers on the heap?
  • sharptooth
    sharptooth over 15 years
    For case (1) it's not necessary, you may want to store an array of void* to be able to just call free() - that's not C++ way of doing things, but might be. For case (2) I meant an array of pointers versus an array of actual objects. If objects are really large storing pointers save much stack space.
  • strager
    strager over 15 years
    @caparcode, Actually, QObjects are not copyable. That includes GUI elements and very few graphic classes, and some other stuff. Other classes may be non-copyable too, for whatever reason.
  • mk12
    mk12 almost 11 years
    Well, Java doesn't "have" pointers because everything other than a primitive is implicitly a pointer.
  • A.R.
    A.R. over 10 years
    This isn't an answer. The point of this site is to help people learn more, not to dismiss them when you can't articulate your thoughts.
  • CiscoIPPhone
    CiscoIPPhone over 10 years
    @A.R. Hopefully I did let jamolkhon learn not to always use pointers - look at the first sentence to his question. I took that context into account, not just the title. Besides, other questions list some of the uses.
  • A.R.
    A.R. over 10 years
    I took the last sentence into account, you know, the question part.
  • CiscoIPPhone
    CiscoIPPhone over 10 years
    @A.R. So did I. But taking context into account can help you create an answer which is more useful than just looking at the sentence which contains the question - especially if other people have already addressed that.
  • A.R.
    A.R. over 10 years
    Yeah I learned a lot from your very useful answer. Now I am an expert on when and when not to use pointers. I especially like how you cross reference your breadth of knowledge on the topic of pointers with other "people who have already addressed that" by providing links. Amazing!
  • CiscoIPPhone
    CiscoIPPhone over 10 years
    @A.R. There's no need to be snarky. Other people felt my answer was helpful, if you don't that is fine, just downvote and move on.
  • A.R.
    A.R. over 10 years
    Who's being snarky? This answer is so useful that I can actually apply it to any question I would ever have about anything: If I don't know how to use it, then I should not use it, and then by not using it or knowing how to use it, it will become apparent when and how it should be used! PURE GENIUS! My only wish is that I could upvote TWICE!
  • CiscoIPPhone
    CiscoIPPhone over 10 years
    @A.R. OP came to the conclusion that he should always use pointers, I feel my answer is helpful for this specific case. I've seen this many times, even in professional code bases where people use pointers when there is no need. My advice is don't use them always, and for the cases you do need them it will become apparent. It can't be applied to all questions - perhaps only the ones where people have come to the conclusion that something should always be used that can actually be detrimental.
  • underscore_d
    underscore_d almost 8 years
    But you can allocate something on the stack and then use it later polymorphically by passing a reference or pointer to your function/container/whatever. Storage duration and polymorphism are orthogonal concepts. Yet people continue to answer questions about why one might allocate via pointer by citing polymorphism as an advantage, without ever explaining why the two are related (they're not).
  • underscore_d
    underscore_d almost 8 years
    "two orthogonal things" - finally, someone said it! c.f. I would add to point 2 that accessing by reference/pointer (=address) enables polymorphism, regardless of how the object was allocated - contrary to the baffling number of posts I see implying that a valid reason for dynamic allocation is to grant polymorphic behaviour - which is not required, not an argument, and completely unrelated.