views:

1862

answers:

14

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/tutorials/qt4tutorial/painting/) where QPaint object is created on the stack. So now I am confused. When should I use pointers?

+4  A: 

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
}
anon
How about the limitations of stack?
presario
what limitation would that be?
anon
well i mean on some systems if not all the size of the stack is limited isn't it?
presario
@presario: the stack size is limited, but for the normal reasons you do not have to use pointers for this case
Ahmed Said
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.
Nate
@nate nobody is suggesting otherwise
anon
In 15 years I don't think I've ever run out of stack that wasn't something like a stupid recursion bug.
Rob K
+13  A: 

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.
bb
I think the most important point of pointers is controlling the lifetime of objects
Edison Gustavo Muenz
Point #2 applies particularly to Qt as most Qt graphics related objects are not copyable.
Arnold Spence
@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.
strager
Vadim Ferderer
A: 

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

Just about everything you say here is incorrect.
anon
Yep, you're very wrong.
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?
A: 

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.

Mark Ingram
int x; int* pointer_to_x = You're repeating the OP's confusion between pointers and heap allocation.
Pete Kirkham
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
+2  A: 

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.

sharptooth
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.
anon
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.
sharptooth
+19  A: 

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.

CiscoIPPhone
Who downvoted this?
+5  A: 

This link might help you. Check this. when-to-use-pointers-and-when-not-to

aJ
+2  A: 

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.

Mr Fooz
It's actually a pretty horrible idea.
Dave Van den Eynde
+1  A: 

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

Dave Van den Eynde
+3  A: 

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

Dan
+1 for the last, bolded, paragraph, because I can't upvote it more myself.
David Thornley
+4  A: 

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.

ajanicij
A: 

using pointers is connected with two orthogonal things:

  1. 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).

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

oo_olo_oo
A: 

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.

dicroce
A: 

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

swongu