Op 11-Jun-12 11:23, Juha Nieminen schreef:
> Paavo Helde<
myfir...@osa.pri.ee> wrote:
>> This is about the worst advice one could give, exactly because of the
>> implicit conversion to const char*. This means that if some function f()
>> outputs a string, the following code compiles without any warning or
>> error:
>>
>> const char* s = f();
>>
>> Now imagine that f() returned a char* pointer originally (e.g. to a
>> static buffer, or to a string literal), and was later upgraded to return
>> a CString. I think this is exactly what OP wants to do.
>
> I'm not absolutely sure of this, but I have the impression that if he's
> using C++.NET (which isn't a far-fetched assumption given that he is
> developing a Visual C++ project), the string in question would be
> gargabe-collected and hence the above would be safe. CString is probably
> allocating the string using gcnew.
I doubt that (can't check it because I don't have the Professional
Edition of VC2010). Am sure this isn't true for the version of MFC and
ATL that came with VC2005, and I seriously doubt Microsoft would change
this as it would imply you couldn't use MFC or ATL with unmanaged
applications, which would kinda defeat the purpose of including these
libraries in the first place. Note that VC2010 still can produce native
executables which do not require the .NET framework.
As far as the .NET garbage collection thingy is concerned; that doesn't
do anything for raw C++ pointers, the onus is still on the programmer to
take care of the lifetime. I have recently looked in to this for a
project that required C# code to communicate with unmanaged C++ code.
C++/CLI is a schizophrenic language. There is C++ part with C++
semantics and the CLI part with the semantics typical for .NET
languages, including garbage collection. Those two parts are quite
separated and don't mix easily. If you want .NET garbage collection, you
can only use a 'ref class', which defines a .NET class. A 'ref class'
cannot derive from C++ classes, or have C++ class instances as members,
must be instantiated with gcnew and instances must referred by handle
(e.g. my_type^). C++ classes cannot derive from .NET classes or directly
have references to instances of .NET classes (at least not directly at
the language level). Compiling standard C++ code doesn't get you any of
the .NET features. Because of this and the reasons stated above I don't
expect that the CString implementation would be safe to use in the
example posted above.
Given that the OP stated that he is using the Express Edition of VC2010,
using CString isn't an option, using basic_string is the only choice
that is supported out-of-the-box (unless he gets a copy of a suitable
version of the MFC/ATL library and manages to use it with the Express
Edition).