With great power comes great responsibility

C++ itself is a pretty complex language, and C++/CLI, with its own baggage of things like handles and managed references doesn’t make it easy to read or debug code at a glance. Here’s a piece of code that had me head-scratching for a while.

enum class Options { Yes, No, Maybe};

void Func(Options ^g)
   Console::WriteLine(g == Options ::Yes);

void Func()

If you run the above piece of code, it will print False. Pretty weird huh?

It seems inexplicable, until you notice the caret sign (^) before g in the formal parameter declaration of Func. The caret symbol causes the enum to be boxed, and the == operator then does a reference comparison. Which will obviously fail, because a valid reference handle will never be zero. To verify that it is indeed comparing addresses, try changing the code to read  g->Equals(Options::Yes) – you’ll find that it prints True. Of course, taking away the caret sign will work as well, and that is what the programmer intended in this particular case – the caret was a typo.

I’m surprised that the compiler doesn’t offer much of a help here, not even a warning. Especially the part where it does a reference comparison between a handle and an int. The equivalent C# code

((object)g) == Options.Yes

fails with a compiler error.

With great power comes great responsibility, I guess 🙂

One thought on “With great power comes great responsibility”

Leave a Reply

Your email address will not be published. Required fields are marked *