References are actually pointers. You just don't have to type all the *s and &s to use them.
The primary purpose of a pointer is to access
dynamic data. For example, say you wish to read a WAV file into memory (for example, the ever obnoxious
C:\WINDOWS\Media\tada.wav) and do some processing on it.
You could just declare an array of
C:\WINDOWS\Media>dir tada.wav
Volume in drive C is Ceres
Volume Serial Number is D000-0000
Directory of C:\WINDOWS\Media
08/29/2002 07:00 AM 171,100 tada.wav
1 File(s) 171,100 bytes
0 Dir(s) <censored> bytes free
bytes:
unsigned char file_data[ 171100 ];
But what if you want to be able to load
any WAV file (as specified by the user), or some really,
really big file? For that you'll need to use
malloc() or
new to get the memory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
void* load_file( const string& filename, streamsize& filesize )
{
char* result;
ifstream inf( filename.c_str(), ios::binary );
if (!inf) return NULL;
inf.seekg( 0, ios::end );
filesize = inf.tellg();
inf.seekg( 0, ios::beg );
result = new (nothrow) char[ filesize ];
if (result)
{
inf.read( result, filesize );
}
inf.close();
return (void*)result;
}
|
This is, obviously, a cheesy example, but hopefully it demonstrates the idea well enough.
Hope this helps.
[edit] I'm still learning to spell, apparently... [/edit]
[edit 2] Actually, references can be optimized much more readily than pointers too... [/edit]