StrBuf::StringInit()
Initialize a StrBuf.
|
Virtual? |
No |
|
|
Class |
||
|
Arguments |
None |
|
|
Returns |
|
Notes
StringInit()
initializes the StrBuf to contain a zero-length null
buffer.
Normally when a StrBuf is created, it is initialized using
the StrBuf constructor. However, there may be specialized
cases where memory has already been allocated for a StrBuf
instance, but the memory was not allocated through the normal mechanisms
that would result in the StrBuf constructor initializing the
instance. For these specialized cases, StringInit() is
appropriate for initializing a StrBuf instance.
After a StrBuf has been used, calling StringInit() for the
instance can result in a memory leak. Specifically, once the
buffer member has been pointed to memory other than
nullStrBuf, calling StringInit() for the
instance will abandon the memory.
In most cases, it is preferable to use an alternative such as one of the following:
sb1 = StrRef::Null(); sb2.Clear(); sb2.Terminate(); sb3.Set( "" ); sb4 = "";
See also
StrBuf::Clear() StrBuf::Set() StrBuf::Terminate() StrBuf::operator =( char *
) StrRef::Null()
Example
#include <iostream>
#include <errno.h>
#include <stdhdrs.h>
#include <strbuf.h>
#define NSTRBUFS 5
#define CHUNKSIZE 1024
#define STRBUFSIZE sizeof( StrBuf )
int main( int argc, char **argv )
{
char chunk[ CHUNKSIZE ];
int chunkFree = CHUNKSIZE;
char *pchunkStart = &chunk[ 0 ];
char *pchunk;
int iStrBuf;
// Initialize the StrBufs in the chunk.
for ( iStrBuf = 0, pchunk = pchunkStart;
iStrBuf < NSTRBUFS;
iStrBuf, pchunk += STRBUFSIZE )
{
// Ensure that there's enough free left in the chunk for a StrBuf.
if ( (chunkFree -= STRBUFSIZE) < 0)
{
cout << "Not enough free left in the chunk!\n";
return ENOMEM;
}
// Initialize and set the value of the StrBuf.
((StrBuf *)pchunk)->StringInit();
*(StrBuf *)pchunk << iStrBuf + 73;
}
// Print the StrBufs. Do this in a separate loop so as to provide
// some evidence that the above loop didn't corrupt adjacent StrBufs.
for ( iStrBuf = 0, pchunk = pchunkStart;
iStrBuf < NSTRBUFS;
iStrBuf, pchunk += STRBUFSIZE )
{
cout << "StrBuf " << iStrBuf + 1 << " contains \"";
cout << ((StrBuf *)pchunk)->Text() << "\"\n";
}
}
Executing the preceding code produces the following output:
StrBuf 1 contains "73" StrBuf 2 contains "74" StrBuf 3 contains "75" StrBuf 4 contains "76" StrBuf 5 contains "77"






