1

Can anyone tell me what the difference is between these 2 lines of code, which one is better to use?

    System::String ^MyStr = gcnew System::String(MyStr); 

    System::String ^MyStr; 
Gary
  • 318
  • 3
  • 14
  • Please add a tag indicating which programming language you are asking about. – Matt Ball Jun 10 '11 at 16:55
  • They are the same, both produce a nullptr. The first one however will make whomever maintains your code some day find you and hurt you. That ought to answer the question. – Hans Passant Jun 11 '11 at 15:39

2 Answers2

3

Those lines are not equivalent. In the first one, you will get an exception beacuse you're trying to create a String from an uninitialized tracking handle (MyStr). In the second one, MyStr is declared, not defined, it points to garbage and will throw an exception if you attempt to use it. Which one you should use depends on the rest of the code

dario_ramos
  • 7,118
  • 9
  • 61
  • 108
  • 1
    The second one is uninitialized. It may or may not have the value `nullptr`, but it's unusable until initialized in any case. – ildjarn Jun 10 '11 at 19:01
  • 1
    One more correction ;-] The second one does point to garbage, but may throw `NullReferenceException` _or_ `AccessViolationException` if you dereference it. – ildjarn Jun 10 '11 at 20:38
  • 1
    @dario, @ildjarn: You guys all missed the point, IMO. The first one doesn't point to a newly-created string, because the string constructor fails, because its argument is garbage. – Ben Voigt Jun 11 '11 at 13:16
1

The second one creates a new handle variable. If it's a local variable, then as @dario_ramos says, it's uninitialized, and your program will likely crash if you try to use the handle before assigning it. If it's a member variable or global, then it will be nullptr.

The first one is similar, although it can only be used for locals or globals (member variables use the ctor-initializer syntax in C++/CLI just like plain C++), and does exactly what you're not permitted to do. It reads the brand new uninitialized handle and passes it to the System::String constructor. If by chance the constructor finishes, a handle to the newly constructed String will be placed into the variable as part of initialization. But because the constructor is trying to make a copy of random garbage (if it's a local) or nullptr (if a global), most likely it will simply crash.

It's a bad idea to use the value of any variable in its own initializer (sometimes you need to use the address, never the value).

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720