Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use pointers in C++

I just started learning about pointers in C++, and I'm not very sure on when to use pointers, and when to use actual objects.

For example, in one of my assignments we have to construct a gPolyline class, where each point is defined by a gVector. Right now my variables for the gPolyline class looks like this:

private:
vector<gVector3*> points;

If I had vector< gVector3 > points instead, what difference would it make? Also, is there a general rule of thumb for when to use pointers? Thanks in advance!

like image 804
Mel Avatar asked Jan 30 '10 20:01

Mel


People also ask

When should pointers be used in C?

Pointers are used with data structures. They are useful for representing two-dimensional and multi-dimensional arrays. An array, of any type, can be accessed with the help of pointers, without considering its subscript range. Pointers are used for file handling.

When should be pointers used what are the reasons?

Pointers are used to store and manage the addresses of dynamically allocated blocks of memory. Such blocks are used to store data objects or arrays of objects. Most structured and object-oriented languages provide an area of memory, called the heap or free store, from which objects are dynamically allocated.

Where are pointers used in C?

C uses pointers to create dynamic data structures -- data structures built up from blocks of memory allocated from the heap at run-time. C uses pointers to handle variable parameters passed to functions. Pointers in C provide an alternative way to access information stored in arrays.


2 Answers

The general rule of thumb is to use pointers when you need to, and values or references when you can.

If you use vector<gVector3> inserting elements will make copies of these elements and the elements will not be connected any more to the item you inserted. When you store pointers, the vector just refers to the object you inserted.

So if you want several vectors to share the same elements, so that changes in the element are reflected in all the vectors, you need the vectors to contain pointers. If you don't need such functionality storing values is usually better, for example it saves you from worrying about when to delete all these pointed to objects.

like image 102
sth Avatar answered Oct 13 '22 21:10

sth


Pointers are generally to be avoided in modern C++. The primary purpose for pointers nowadays revolves around the fact that pointers can be polymorphic, whereas explicit objects are not.

When you need polymorphism nowadays though it's better to use a smart pointer class -- such as std::shared_ptr (if your compiler supports C++0x extensions), std::tr1::shared_ptr (if your compiler doesn't support C++0x but does support TR1) or boost::shared_ptr.

like image 26
Billy ONeal Avatar answered Oct 13 '22 23:10

Billy ONeal