Reputation: 40947
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
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
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
Reputation: 7309
If you mean C++/CLI...
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.Upvotes: 1
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