Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use pointers, and when not to use them

Tags:

c++

pointers

I'm currently doing my first real project in C++ and so, fairly new to pointers. I know what they are and have read some basic usage rules. Probably not enough since I still do not really understand when to use them, and when not.

The problem is that most places just mention that most people either overuse them or underuse them. My question is, when to use them, and when not?.

Currently, in many cases i'm asking myself, should I use a pointer here or just pass the variable itself to the function.

For instance, I know that you can send a pointer to a function so the function can actually alter the variable itself instead of a copy of it. But when you just need to get some information of the object once (for instance the method needs a getValue() something), are pointers usefull in that case?

I would love to see either reactions but also links that might be helpfull. Since it is my first time using C++ I do not yet have a good C++ book (was thinking about buying one if I keep on using c++ which I probably will).

like image 739
bastijn Avatar asked Aug 25 '09 12:08

bastijn


People also ask

When should you use pointers?

Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.

Why do we not use pointers?

pointers need so memory spaces at the runtime. to reduce the usage of memory spaces java does not support pointers. and also pointers take more time at the run time. Pointer lead to confusion for a programmer.

Are pointers necessary?

Most uses of pointers in C++ are unnecessary. Unlike other languages, C++ has very strong support for value semantics and simply doesn't need the indirection of pointers.


1 Answers

From the c++ faq:

Use references when you can, and pointers when you have to.

https://isocpp.org/wiki/faq/references#refs-vs-ptrs

like image 125
Kristian Avatar answered Sep 28 '22 18:09

Kristian