RH> KK> why would you want to use strdup() in C++??
RH> I guess I want(ed) to since I hadn't, and haven't really,
RH> reached the class libraries yet, in this stage of my
RH> "education". :-)
You should be getting C_ECHO too, then. There is some effort
made to keep C and C++ topics separate. You would find that
strdup() is not in the standard, but that your own function
to do the job would do as well, probably, and eliminate any
questions of safety. Note that in C, you would use malloc()
and test for NULL before attempting to use strcpy(), while
you would use try and catch to do the same in C++.
// Returns a pointer to duplicate string, or NULL on failure.
// Requires a valid pointer to a valid char array and
// sufficient memory to hold the string to result in success.
// User is responsible for performing delete[] on returned char*.
char *Mystrdup(char *szString)
{
char *szCopy = 0;
if(szString && *szString)
{
try {
szCopy = new char[strlen(szString) + 1];
strcpy(szCopy, szString);
}
catch(CMemoryException* e) {
szCopy = 0;
}
}
return szCopy;
}
RH> KK> Class Libraries often provide safe, and often
RH> KK> superior, support for many data functions.
RH> Although I believe I will allways be somewhat reluctant
RH> to link in yet another library if a simple char* would do
RH> the job, the comment is appreciated!
Since the class libraries are basically an integrated package
for calling the standard libraries, you are actually linking
in very little extra, and gaining a great deal of
functionality for very little overhead.
It IS good to learn the C libraries, the hows and the whys,
but that sort of defeats the purpose of OOD, which seeks to
supply integrated data objects instead of data objects and
a collection of separate functions.
The Mystrdup() I listed above, or rather, a properly written
equivalent, ( ), would be invoked by the simple
expedient of using the String class with the = operator.
[ MSVC++ code with a twist of lime ]
CString Duplicate = Mystring;
cout << "Duplication " <<
(
Duplicate.GetLength()
? "successful."
: "failed."
)
<< '\n' << flush;
=-=-=
You will, of course, need to know the basic C functions in
order to be able to construct your own classes which call
upon them, so an understanding of C is essential to an
ability to program in C++, to some extent. If, however, you
are content to use the classes supplied by your compiler,
then you will never need to know the base functions, and you
may still call yourself a C++ programmer in all honesty.
In either case, you would likely avoid any functions which
relied on malloc() unless there were no alternatives
available. You would especially avoid anything not in the
ANSI standard, unless you had absolutely no concerns about
ever changing compilers or platforms with that code.
> ] Wait a minute... ///\oo/\\\ Almonds don't have legs.........
---
---------------
* Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)
|