> Wouldn't this be safe (for malloc)??
>
> CString str;
> char *tmp = NULL;
>
> try
> {
> str = "Hello";
> tmp = (char *)malloc(str.GetLength() + 1);
> if (tmp)
> {
> wcstombs(tmp, str, str.GetLength());
> LibraryFuncCall(tmp);
> free(tmp);
> tmp = NULL;
> }
> }
> catch(...)
> {
> if (tmp)
> free(tmp);
> }
This is exception safe, but there are two problems with it:
1. You're re-inventing what the C++ language already provides by the dtors.
The part in catch(...) is really a task for a dtor. The small objects which
do such management in their dtor are called (you guessed it) smart pointers.
Believe me, if you don't use them already, smart pointers are the most
valuable programming resource you can get familiar with. There are all
flavors of them, COM smart pointers, memory manager smart pointers (like
std::auto_ptr, Boost.smart_ptr, and Loki's smart pointers), and custom ones
(the ones that you write to do your custom cleanup. They are an important
part of the Resource Acquisition Is Initialization (RAII) paradigm, and a
must-learn technique. With a smart pointer, the code will be simplified to
something like:
str = _T("Hello");
SMART_PTR ptr( str.GetLength() );
wcstombs( ptr, str, str.GetLength() );
LibraryFuncCall( ptr );
Note that this code is as exception safe as your code, and highly more
efficient (because it doesn't use try/catch which add a lot of code the
compiler must generate.)
2. You're using the heap where stack allocation does just fine. ATL's
conversion macros do use stack allocation, so are even more efficient and
simple to use. Using them, the code is reduced to:
USES_CONVERSION;
str = _T("Hello");
LibraryFuncCall( T2CA( str ) );
BTW, without the _T macro, your code will not compile in Unicode builds!
-------------
Ehsan Akhgari
Farda Technology (http://www.farda-tech.com/)
List Owner: [EMAIL PROTECTED]
[ Email: [EMAIL PROTECTED] ]
[ WWW: http://www.beginthread.com/Ehsan ]
Physician, heal thyself: then you will also heal your patient. Let it be his
best cure to see with his eyes the man who heals himself.
-Thus Spoke Zarathustra, F. W. Nietzsche