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?
-
The QT tutorials create the QPaint object on the stack because the QPaint object's useful life is known at compile time and is exactly bounded by a matched pair of {}.– Thomas L HoladayCommented Mar 19, 2009 at 5:58
-
The same is holds for QPen, QPainter, and QApplication.– Thomas L HoladayCommented Mar 19, 2009 at 6:01
-
What is great to know about pointer is that we now have in C++ some safe implementation of pointers like unique_ptr or weak_ptr, when you need to use pointer, you need to use them (with some rare exception on low level code)– MokaTCommented Jul 20, 2015 at 13:33
14 Answers
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.
-
6This 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.– A.R.Commented Mar 13, 2014 at 2:09
-
@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. Commented Mar 13, 2014 at 20:46
-
1@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. Commented Mar 14, 2014 at 0:38
-
1@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. Commented Mar 14, 2014 at 1:26
-
1@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. Commented Mar 14, 2014 at 15:33
Main reasons for using pointers:
- control object lifetime;
- can't use references (e.g. you want to store something non-copyable in vector);
- you should pass pointer to some third party function;
- maybe some optimization reasons, but I'm not sure.
-
4I think the most important point of pointers is controlling the lifetime of objects Commented Mar 18, 2009 at 13:10
-
Point #2 applies particularly to Qt as most Qt graphics related objects are not copyable. Commented Mar 18, 2009 at 20:41
-
@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.– stragerCommented Mar 19, 2009 at 5:34
-
References can be stored in vector: std::vector< boost::optional<T&> > Commented Apr 10, 2009 at 3:35
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++.
-
3+1 for the last, bolded, paragraph, because I can't upvote it more myself. Commented Mar 18, 2009 at 15:11
-
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). Commented Jul 9, 2016 at 9:47
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.
Which tutorials would those be? Actually, the rule is that you should use pointers only when you absolutely have to, which is quite rarely. You need to read a good book on C++, like Accelerated C++ by Koenig & Moo.
Edit: To clarify a bit - two instances where you would not use a pointer (string is being used here as an exemplar - same would go for any other type):
class Person {
public:
string name; // NOT string * name;
...
};
void f() {
string value; // NOT string * value
// use vvalue
}
-
-
what limitation would that be?– anonCommented Mar 18, 2009 at 13:01
-
well i mean on some systems if not all the size of the stack is limited isn't it?– JamolCommented Mar 18, 2009 at 13:04
-
@presario: the stack size is limited, but for the normal reasons you do not have to use pointers for this case– AhmedCommented Mar 18, 2009 at 13:10
-
Pointers are a tool. Limiting their use to "only when you absolutely have to" is too strict. With proper design considerations, they can be a key to a very maintainable and robust design.– NateCommented Mar 18, 2009 at 13:46
You usually have to use pointers in the following scenarios:
You need a collection of objects that belong to different classes (in most cases they will have a common base).
You need a stack-allocated collection of objects so large that it'll likely cause stack overflow.
You need a data structure that can rearrange objects quickly - like a linked list, tree ar similar.
You need some complex logic of lifetime management for your object.
You need a data structure that allows for direct navigation from object to object - like a linked list, tree or any other graph.
-
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.– anonCommented Mar 18, 2009 at 14:39
-
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. Commented Mar 19, 2009 at 4:55
In addition to points others make (esp. w.r.t. controlling the object lifetime), if you need to handle NULL objects, you should use pointers, not references. It's possible to create a NULL reference through typecasting, but it's generally a bad idea.
Generally use pointers / references to objects when:
passing them to other methods
creating a large array (I'm not sure what the normal stack size is)
Use the stack when:
You are creating an object that lives and dies within the method
The object is the size of a CPU register or smaller
-
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? Commented Mar 18, 2009 at 22:23
I actually use pointers in this situation:
class Foo
{
Bar* bar;
Foo(Bar& bar) : bar(&bar) { }
Bar& Bar() const { return *bar; }
};
Before that, I used reference members, initialized from the constructor, but the compiler has a problem creating copy constructors, assignment operators, and the lot.
Dave
using pointers is connected with two orthogonal things:
Dynamic allocation. In general, you should allocate dynamically, when the object is intended to live longer that the scope in which it's created. Such an object is a resource which owner have to be clearly specified (most commonly some sort of smart pointer).
Accessing by address (regardless of how the object was created). In this context pointer doesn't mean ownership. Such accessing could be needed when:
- some already existing interface requires that.
- association which could be null should be modeled.
- copying of large objects should be avoided or copying is impossible at all, but the reference can't be used (e.g., stl collections).
The #1 and #2 can occur in different configurations, for example you can imagine dynamically allocated object accessed by pointer, but such the object could also by passed by reference to some function. You also can get pointer to some object which is created on the stack, etc.
-
"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. Commented Jul 9, 2016 at 9:52
Pass by value with well behaved copyable objects is the way to go for a large amount of your code.
If speed really matters, use pass by reference where you can, and finally use pointers.
If possible never use pointers. Rely on pass by reference or if you are going to return a structure or class, assume that your compiler has return value optimization. (You have to avoid conditional construction of the returned class however).
There is a reason why Java doesn't have pointers. C++ doesn't need them either. If you avoid their use you will get the added benefit of automatic object destruction when the object leaves scope. Otherwise your code will be generating memory errors of various types. Memory leaks can be very tricky to find and often occur in C++ due to unhandled exceptions.
If you must use pointers, consider some of the smart pointer classes like auto_ptr. Auto destruction of objects is more than just releasing the underlying memory. There is a concept called RAII. Some objects require additionally handing on destruction. e.g. mutexes and closing files etc.
-
1Well, Java doesn't "have" pointers because everything other than a primitive is implicitly a pointer.– mk12Commented Aug 19, 2013 at 0:18
Use pointers when you don't want your object to be destroyed when the stack frame is emptied.
Use references for passing parameters where possible.
-
int x; int* pointer_to_x = &x; You're repeating the OP's confusion between pointers and heap allocation. Commented Mar 18, 2009 at 13:17
-
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. Commented Mar 18, 2009 at 15:10
Speaking about C++, objects created on the stack cannot be used when the program has left the scope it was created in. So generally, when you know you don't need a variable past a function or past a close brace, you can create it on the stack.
Speaking about Qt specifically, Qt helps the programmer by handling a lot of the memory management of heap objects. For objects that are derived from QObject
(almost all classes prefixed by "Q
" are), constructors take an optional parameter parent. The parent then owns the object, and when the parent is deleted, all owned objects are deleted as well. In essence, the responsibility of the children's destruction is passed to the parent object. When using this mechanism, child QObject
s must be created on the heap.
In short, in Qt you can easily create objects on the heap, and as long as you set a proper parent, you'll only have to worry about destroying the parent. In general C++, however, you'll need to remember to destroy heap objects, or use smart pointers.