By default you should use nothing, only static allocation:
QPushButton button;
QApplication app(argc,argv);
std::string s;
int a = 0;
Class/struct members are accessed through .
, as in : s.append( "test" )
When you pass it to a function, if you don't want a copy, use a reference
void myFunction( std::string & s ){}
myFunction( s );
If you don't want to modify the parameter but still don't want a copy, use a const reference:
void myFunction( const std::string & s ) {}
myFunction( s ); // we know s won't be modified
That's the basic, what you use by default. You see, it's quite simple. The variables are automatically freed when they go out of scope.
Then comes the pointers. You need to use pointers to allow dynamically the memory on the heap or free store.
int * p = new int[4]; // allow 4 doubles on the free store
p is the address of the first element of the 4 ints. *p
is the value of the first int. In our example, p[1] gives the values of the second int. Class/struct members are accessed through ->
(instead of .
). ->
is the equivalent of (*variable).
If you have a variable allocated statically as:
int i = 0;
then &i
is the address and i
is the value.
You may need pointers with variables that are not scoped-bound, with functions that take addresses as arguments, with polymorphism ( a child class pointer into a base class pointer )
Contrary to static allocation, you need to explicitly destroy pointers. Hence you use
delete[] p; // allocated with new[]
delete p2; // allocated with new
This is where you can get memory leaks, if you forget to delete the memory.
This is why "smart pointers" where invented, these are pointers that will automatically delete their content when nobody needs to use them anymore. For instance, boost::shared_ptr or maybe your compiler support tr1::shared_ptr.
Used like this:
boost::shared_ptr< int > a( new int( 42 ) );
And no need to delete it