There are three fundamental properties of which a computer program must keep track when it stores data.
- Where the information is stored
- What value is kept there
- What kind of information is stored
You have used one strategy for accomplishing these ends: definining a simple variable. The declaration statement provides the type and a symbolic name for the value. It also causes the program to allocate memory for the value and to keep track of the location internally.
Let's look at a second strategy now, one that becomes particulary important in developing C++ classes. This strategy is based on pointers, which are variables that store addresses of values rather then the values themselves.
To explicitely find the address of a variable you just apply the address operator, represented by &, to a variable to get its location. for example if home is a variable, &home is its address.
Pointers and the C++ Philosophy
Object oriented programming differs from traditional procedural programming in that OOP emphasizes making decisions during runtime instead of during compile time.
Runtime decisions provide the flexibility to adjust to current circumstances.
For example consider allocating memory for an array. The traditional way is to declare an array. To declare an array in C++ you have to commit yourself to a particular array size. Thus, the array size is set when the program is compiled. it is a compile time decision. Perhaps normally your program has enough on a array that has a size of 20 elements, but in some exeptional case it needs 100 elements. if you let the compiler decide, you have to reserve 100 elements to store the array, while your program 80% of the time does not use this size, a waste of memory!
OOP tries to make a program more flexible by delaying such decisions until runtime. That way you can tell your program while running you this time need an array of 200 elements instead of the normally used 20.
The C++ method that makes this possible as you soon see involves the keyword new to request the correct amount of memory and using pointers to keep track of where the newly allocated memory is found.
A special type of variable, the pointer holds the address of a value. Thus the name of the pointer represents the location. Applying the * operator, the same as multiply, called the indirect value or dereferencing operator yields the value at the location. (pointed to by the pointer variable);
C++ uses the context to determine whether you mean multiplication or dereferencing. Suppose for example, manly is a pointer. In that case, manly represents an address, and *manly represents the value at that address.
int updates = 6; // declare a variable
int * p_updates; // declare a pointer to int
p_updates = &updates;
cout << *p_updates;
cout << updates;
As you can see, the int variable updates and the pointer variable p_updates are just two sides of the same coin. The updates variable represents the value as primary and uses the & operator to get the address, whereas the p_updates variable represents the address as primary and uses the * operator to get the value. Because p_updates point to updates, *p_updates and updates are completely equivalent! You can use *p_updates exactly as you would use a type int variable. You can even assign values to *p_updates. Doing so changes the value of the pointed-to value, updates.
Let's examine the process of declaring pointers. A computer needs to keep track of the type of value to which a pointer refers. For example, the address of a char typically looks the same as the address of a double, but char and double use different numbers of bytes and different internal formats for storing values.
Therefor a pointer declaration must specify what type of data to which the pointer points.
For example:
int * p_updates;
This states that the combination * p_updates is type int. Because you use the * operator by applying it to a pointer, the p_updates variable itself MUST be a pointer. We say that p_updates points to type int.
We also say that the type for p_updates is pointer-to-int or, more concisely, int *. To repeat: p_updates is a pointer(an address) and *p_updates is an int and not a pointer!
Programmers use different notations for pointers
int *ptr;
int* ptr;
int * ptr;
I use the second notation, because it says a type pointer to int.
Beware of this example, it's a classical mistake:
int* p1, p2;
Makes p1 a pointer to int, but p2 an ordinary int variable!
You use the same syntax to declare pointers to other types:
double* tax_ptr; // tax_ptr points to type double
char* str; // str points to a type char
Because you declare tax_ptr as pointer-to-double, the compiler knows that *tax_ptr is a type double value. That is, it knows that *tax_ptr respresents a number stored in the floating point format that occupies (on most systems) 8 bytes. A pointer variable is NEVER simply a pointer. It is always a pointer to a specific type. tax_ptr is type pointer-to-double ( or type double*) and str is type pointer-to-char(or char*). Although both are pointers, they are pointers to two different types. Like arrays, pointers are based on other types.
Note that pointer addresses themself not tell anything about the size of the object or the data type they point to. Usually addresses stored in the pointer are equal sized. on most systems two or four bytes.
POINTER DANGER
Danger awaits those who incautiously use pointers. One extremely important point is that when you create a pointer in C++, the computer allocates memory to hold an address, but it does NOT allocate memory to hold the data to which the address points. Creating space for the data involves a separate step. Omitting that step, as in the following, is an invitation to disaster!
long* fellow; // create a pointer-to-long
*fellow = 223323 // place a value in never-never land
Sure fellow is a pointer. But where does it point? The code failed to assign an address to fellow. So where is the value 223323 placed? We can't say. Because fellow wasn't initialized, it could have any value. Whatever that value is, the program interprets it as the address at which to store 223323. If fellow happens to have the value 1200, then the computer attempts to place data at address 1200. even if that happens to be an address in the middle of your program code. Changes are that wherever fellow points, that is not where you want to put the number 223323. This kind of error can produce some of the most insidious and hard-to-trace bugs!
POINTER GOLDEN RULE
Always initialize a pointer to a definate and appropriate address before you apply the dereferencing operator (*) to it!
Pointers and Numbers
Pointers are NOT integers, even though computers typically handle addresses as integers. Conceptually, pointers are distinct types from integers. Integers are numbers you can add, subtract, divide and so on. But a pointer describes a location, and it does not make sense for example to multiply two locations by eachother. In terms of operations you can perform with them, pointers and integers are different from eachother. Consequently you can't simply assign an integer to a pointer:
int* pt;
pt = 0xB8000000; // type mismatch
Here, the left side is a pointer to int, so you can assign it an address, but the right side is just an integer. But nothing in the statement tells the program that this number is an address. If you want to use a numeric value as an address, you should use a type cast to convert the number to the appropriate address type:
int* pt;
pt = (int *) 0xB8000000; // types now match
Operator new:
int* pt = new int; // allocate space for an int
new creates memory to hold the int, and returns a pointer to the memory it created, somethimes called the heap.
It does this at RUNTIME, so when your program starts running the memory is created, instead of letting the compiler choose the memory when you use ordinary variables!
The pointer pt point to a data object. Without the pointer you cannot access the memory where the int is stored. The memory allocated by new is also unamed. so the pointer to it is really the only way to reach that memory!
Out of Memory NULL POINTER
It's possible that a computer might not have sufficient memory available to satisfy a new request! When this is the case, new returns the value 0.
In C++, a pointer with the value 0 is called the null pointer.
C++ guarantees the null pointer never points to valid data, so it is often used to indicate failure for operators or functions that otherwise return usable pointers. After you learn about if statements, you can check to see if new returns the null pointer and thus protects your program from attempting to exceed its bounds.
In addition to returning a null pointer upon failure to allocate memory, new might throw a bad_alloc exception.
Freeing Memory with delete
Using new to request memory when you need it is just the more glamorous half of the C++ memory-management package. The other half is the delete operator, which enables you to return memory to the memory pool when you are finished with it. That is an important step toward making the most effective use of memory!
Memory that you return, or free, can then be reused by other parts of the program. You use delete by following it with a pointer to a block of memory that was originally allocated with new:
int* ps = new int; // allocate memory with new
... // use the memory
delete ps; // free the memory with delete when done
This removes the memory to which ps points!; it does not remove the pointer ps itself. You can reuse ps, for example, to point to another new allocation.
You should ALWAYS balance a use of new with the use of delete; otherwise you can wind up with a memory leak--that is, memory that has been allocated but can no longer used. If a memory leak grows too large, it can bring a program seeking more memory to a halt.
You should use delete only to free memory allocated with new. However it is save to apply delete to a null pointer.
Abonneren op:
Reacties posten (Atom)
Geen opmerkingen:
Een reactie posten