Get the 'L' out of here!

  • Thread starter Thread starter Peter Oliphant
  • Start date Start date
P

Peter Oliphant

The following line of code:

m_Font = gcnew System::Drawing::Font( L"Arial", 10 ) ;

also works like this:

m_Font = gcnew System::Drawing::Font( "Arial", 10 ) ;

Note that the 'L' in front of "Arial" is missing in the second version. What
is the difference, if any, between L"string" and "string"?

[==P==]
 
Hi Peter,
The following line of code:

m_Font = gcnew System::Drawing::Font( L"Arial", 10 ) ;

also works like this:

m_Font = gcnew System::Drawing::Font( "Arial", 10 ) ;

Note that the 'L' in front of "Arial" is missing in the second version.
What is the difference, if any, between L"string" and "string"?

Well, the "L" represents a unicode string to the compiler, so it saves a bit
of work. However, neither is optimal in this case. From what I seem to
remember, both will invoke a System::String conversion that converts from an
unmanaged char/wchar_t pointer to a System::String instance (possibly
invoking an encoding conversion), which is totally unnecessary.

Managed C++ actually includes a syntax to ensure you define a literal that
is already a System::String instance and that is subject to all the
interning the runtime uses for this, via de 'S' prefix. So the correct way
really is:

m_Font = gcnew System::Drawing::Font( S"Arial", 10 ) ;

That said, this is unnecessary in C++/CLI, because the compiler can
distinguish the kind of literal from context, I believe, and use a managed
string literal when necessary.
 
Hi Tomas!
Managed C++ actually includes a syntax to ensure you define a literal that
is already a System::String instance and that is subject to all the
interning the runtime uses for this, via de 'S' prefix. So the correct way
really is:

Yes. This cas the case in VC7(.1) (managed C++) but in C++/CLI MS
changed this behaviour and now completely ignores the prefix for string
literals in conjunction with System::String

See: Porting and Upgrading: String Literal
http://msdn2.microsoft.com/ms235263

The compiler just converts the string literal to an System::String,
regardless of the prefix.

See: System::String Handling in Visual C++
http://msdn2.microsoft.com/ms177218

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 
Hi Jochen,
Yes. This cas the case in VC7(.1) (managed C++) but in C++/CLI MS changed
this behaviour and now completely ignores the prefix for string literals
in conjunction with System::String

I think that was what I meant when I said "That said, this is unnecessary in
C++/CLI, because the compiler can
distinguish the kind of literal from context, I believe, and use a managed
string literal when necessary." :)

The reason I mentioned the 'S' was because I got confused thinking the user
was still doing MC++ development. too much language dyslexia :)

Thanks for pointing it out
 
Back
Top