Konrad
Konrad

Reputation: 40947

Common managed C++ gotchas

What are some of the most common issues to look out for when writing managed-C++ for the first time after almost exclusively working with unmanaged C++?

Upvotes: 2

Views: 401

Answers (4)

Paul Groke
Paul Groke

Reputation: 6447

One gotcha (that just got me): assuming "the destructor can only be executed once". Since the destructor is invoked via Dispose, and Dispose might be called multiple times, this assumption (which is fine for C++) does not hold for C++/CLI.

Upvotes: 0

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

Here's another gotcha: Executing a method on an object does not constitute a reference to the object. This means that during execution of a member method the object but after your last reference to this the object might be cleaned up while the method is still executing and the finalizer may fire.

If your object has any unmanaged state that is cleaned up by finalization or contains any other object with such unmanaged state are you're doing computations on that unmanaged state, be sure to call GC::KeepAlive on this after those unmanaged computations. I now tend to just append GC::KeepAlive to all methods of objects with unmanaged computation.

Upvotes: 1

dario_ramos
dario_ramos

Reputation: 7309

If you mean C++/CLI...

  • Forgetting to use pin_ptr when passing arguments by reference. Related to this, it's vital to understand the difference between a tracking handle and a pointer. See the firsts chapters of Expert C++/CLI.
  • C++/CLI doesn't have C#'s yield construct, which we use a lot when writing Unit Tests with Nunit using the TestCaseSource attribute to generate test case data. This is related to the next one.
  • Implementing System::IEnumerable is sintactically cumbersome. But once you do it once, you have a reference, so it's not that bad.
  • It's very important to understand the difference between destructors and finalizers. For a discussion about this, again, see chapter 4 of Expert C++/CLI

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89172

When you convert a managed delegate to a pointer-to-function using the built-in IJW (It Just Works) technology, the pointer-to-function is not holding a reference to the object that the delegate was from. If you don't arrange to hold a reference some other way, the managed object may be collected, and then when you call the function, you'll get a NullReferenceException.

You run into this a lot if you are making a C-library that takes callbacks, and you want to wrap it in a Managed class. The client to the managed class will provide a delegate, which you convert to the callback. You must also keep a reference to the delegate or target object.

This is true in Managed C++ and C++/CLI.

Upvotes: 2

Related Questions