Dynamic memory allocation¶
new
& delete
¶
new
(operator) has 2 steps:
- allocate space
- call the constructor function
C++
int *p1 = new int // malloc(sizeof(int)); + constructor
int *p2 = new int [10] // continuous space allocated
delete
+ pointer
If delete a constructed type, it will implement D’tor
function
C++
it is safe to delete a p2 = new student [10];
delete p2; // remove the first one
delete[] p2; // remove whole 10 objects
NULL
.
Copy constructor¶
has a unique signature
call by referencecompiler (in-line) would do it automatically.
But how?
- member-wise (versus bit-wise)
if it has a class defined, it will iteratively call its copy function.
It is neccesary to define a copy constructor when you have pointer member or what you don't want to be copied in your class.
C++
A b(a);
A c = a;
// define function passing in value
void f(A aa)
{
}
// return value
A f()
{
A aa(19);
return aa;
}
Assignment: can be done alot of time. Ctor can only be called once.