Bronek Kozicki said:
this is poor design. Try something more along the lines:
No kidding. Yet I haven't seen a decent answer here yet. If you didn't
allocate the string, you have no business deleting it. Period. Establish
memory ownership rules and respect them. Simply comparing to known literal
strings buys you nothing. There are at least a dozen different allocators
out there (alloca, malloc, new, new [], CoTaskAlloc, LocalAlloc, HeapAlloc,
GlobalAlloc, SysAllocString, SafeArrayCreate, ...) and you have to use the
correct matching deallocator. The first four are CRT-specific, so multiple
by about 10 different versions of MSVC, Borland, etc.
Since we're in the C++/CLI newsgroup anyway, let me ask this question. What
happens when your string is part of a System::String? Like
System::String^ str = ....;
pin_ptr<wchar_t> wsz = PtrToStringChars(str);
your_function(wsz);
Do you really want to call delete [] on that string now?
There are two standard memory ownership schemes. Win32 core API uses
caller-managed buffers. The only core Win32 functions that allocate and
free memory are the ones designed for that purpose.
The other scheme is COM-style. If a library wants to accept ownership of
parameters (necessary to avoid marshalling the data back during RPC), then
it specifies that the argument must have been allocated using the functions
it provides (think of BSTR). Any out parameter allocated within the
library, the caller must send back to the library for deallocation. This
also plays well with reference counting.
Of course, GC changes the whole picture.
const char* a = NULL;
const char* const b = "abc";
if (blablabla)
a = new char[1200];
else
a = b;
// do the job
if (a != b)
delete[] a;
B.