Dynamic Memory

new and delete
- C functions
malloc and free can be used to manage memory dynamically
- Dynamic memory management in C++ is accomplished with operators
new and delete
- These operators offer new features in C++
      1)
new automatically determines memory size (no need for sizeof function)
      2)
new and delete operators automatically call constructors/destructors

new operator
    - used to allocate memory for a variable or object
    - just like with
malloc, returns pointer to allocated memory on the heap
    - can also use to allocate arrays of objects or variables
    - constructors of allocated objects are called automatically

delete operator
    - used to free memory for a variable or object
    - can be used to free arrays of objects or variables
    - destructors of freed objects are called automatically

 

Using dynamic allocation
- Letís look at how we can use these new operators in the following example
- We are using the
Array3D class from previous examples

 

#include <iostream>

using namespace std;

 

class Array3D

{

private:

float val[3];

 

public:

 

// Constructor

Array3D( float t1=0.0, float t2=0.0, float t3=0.0 )

{

††† val[0]=t1; val[1]=t2; val[2]=t3;

}

 

// Print method

void Print()

{

††† cout << "val: " << val[0] << ", " << val[1] << ", " << val[2] << endl;

}

 

// Access methods

void setVals( float a, float b, float c ) { val[0]=a; val[1]=b; val[2]=c; }

float *getVals() { return val; }

};

 

main()

{

// new used to create a single object on the heap

// default arguments used in automatic call to constructor

Array3D *aptr1 = new Array3D;

aptr1->Print();

 

// With pointers, we need to dereference (->)

aptr1->setVals( 1.0, 1.0, 1.0 );

aptr1->Print();

 

// new calls Array3D(float,float,float)

Array3D *aptr2 = new Array3D( 1.0, 2.0, 3.0 );

aptr2->Print();

 

// We can also declare arrays of objects...

 

// This will call Array3D() constructor for both

Array3D aarray1[2];

aarray1[0].Print();

aarray1[1].Print();

 

// You can also specify which constructor explicitly

Array3D aarray2[2] =

††† {

††††† Array3D(), Array3D( 1.0, 2.0, 3.0 )

††† };

aarray2[0].Print();

aarray2[1].Print();

 

// We can also allocate arrays of objects

 

// This will call Array3D() constructor for both objects

Array3D *aset1 = new Array3D[ 2 ];

aset1[0].Print();

aset1[1].Print();

 

// Delete objects

delete aptr1;

delete aptr2;

delete[] aset1; // Note brackets when deleting multiple objects

}

 

Output

val: 0, 0, 0

val: 1, 1, 1

val: 1, 2, 3

val: 0, 0, 0

val: 0, 0, 0

val: 0, 0, 0

val: 1, 2, 3

val: 0, 0, 0

val: 0, 0, 0