Archive

Archive for April, 2010

Dynamic Memory Management Overview with C++ 1

April 6, 2010 Leave a comment

Allocating memory

Dynamic Memory allocation is done by using the keyword “new” in c++. When creating dynamic memory a pointer is always needed.  Let us start by looking at one very simple example. (the code below does not deallocate memory which I will get to next.)

main(){
int* iPtr;
iPtr = new int;
*iPtr = 10
cout << *iPtr << endl
}

so there you have it, a simple dynamically allocated int. The program above does not give us any advanges, but I used it since its a good example for learning purposes.

Deallocating memory

It is very important to give the memory back to the OS after we are done with the memory we need. Memory is given back to the OS by using the keyword “delete”. It is very simple to use, in the example I did not deallocate memory back to the OS, which makes it unusable until the OS is restarted.  Here is an modified version of the program above which deallocates memory.

main(){
int* iPtr;
iPtr = new int;
*iPtr = 10
cout << *iPtr << endl
delete *iPtr //simply remove the allocated memory pointed by *iPtr
}
Keep in mind that “delete *iPtr” does not delete the pointer, but it deletes what is it pointing to.
Categories: OOP344

Function Templates Example

April 6, 2010 Leave a comment

It is common to see functions that do almost the same thing but for different data types. We don’t need to write that code many times and just change the data types. The correct solution is to use function templates. I have written a swap function to demonstrate the use of function templates.

template <template T>
void swap(T a, T b){
T temp;
temp = a;
a = b;
b = temp;
}

we the function template above, we can pass it an int or float and the compiler will automatically create separate functions as needed.

Categories: OOP344