Tutorial :c++: when to use pointers?



Question:

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?


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

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  }  


Solution:6

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.


Solution:7

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.


Solution:8

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


Solution:9

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


Solution:10

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.


Solution:11

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.


Solution:12

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.


Solution:13

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.


Solution:14

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »