전체 페이지뷰

2013년 2월 6일 수요일

Pointers and Dynamic Arrays


• A pointer is a memory address, so a pointer provides a way to indirectly name a variable by naming the address of the variable in the computer’s memory.
• Dynamic variables (also called dynamically allocated variables) are variables that are created (and destroyed) while a program is running.
• Memory for dynamic variables is in a special portion of the computer’s memory called the freestore manager. When a program is finished with a dynamic variable, the memory used by the dynamic variable can be returned to the freestore manager for reuse; this is done with a delete statement.
• A dynamically allocated array (also called simply a dynamic array) is an array whose size is determined when the program is running. A dynamic array is implemented as a dynamic variable of an array type.
• A destructor is a special kind of member function for a class. A destructor is called automatically when an object of the class passes out of scope. The main reason for destructors is to return memory to the freestore manager so the memory can be reused.
• A copy constructor is a constructor that has a single argument that is of the same type as the class. If you define a copy constructor, it will be called automatically whenever a function returns a value of the class type and whenever an argument is plugged in for a call-by-value parameter of the class type. Any class that uses pointers and the operator new should have a copy constructor.
• When overloading the assignment operator, it must be overloaded as a member operator. Be sure to check that your overloading works when the same variable is on both sides of the overloaded assignment operator.

class StringClass
{
public:
...
void someProcessing( );
...
StringClass& operator=(const StringClass& rtSide);
...
private:
char *a; //Dynamic array for characters in the string int capacity; //size of dynamic array a
int length; //Number of characters in a
};

StringClass& StringClass::operator=(const StringClass& rtSide)
{
if (this == &rtSide)
//if the right side is the same as the left side
{
return *this;
}
else
{
capacity = rtSide.capacity;
length = rtSide.length;
delete [] a;
a = new char[capacity];
for (int i = 0; i < length; i++)
a[i] = rtSide.a[i];
return *this;
}
}

PFArrayD& PFArrayD::operator =(const PFArrayD& rightSide)
{
if (capacity != rightSide.capacity)
{
delete [] a;
a = new double[rightSide.capacity];
}
capacity = rightSide.capacity;
used = rightSide.used;
for (int i = 0; i < used; i++)
a[i] = rightSide.a[i];
return *this;
}
Note that this also checks for the case of having the same object on both sides of the assignment operator.
PFArrayD::~PFArrayD( )
{
delete [] a;
}

댓글 없음:

댓글 쓰기