General Hints Regarding gcroot and autogcroot

There are a few subtle pitfalls that you should know about when using the gcroot and auto_gcroot templates. As discussed already, in many cases you can use a gcroot or auto_gcroot variable as if it were of the wrapped tracking handle type. However, in a few cases, this is not possible. For example, you cannot invoke a default indexed property via a gcroot or auto_gcroot variable. The following code shows an example:

List<int>A ints = GetIntListFromSomeWhere(); Console::WriteLine(ints[0]); // legal gcroot<List<int>A> ints2 = GetIntListFromSomewhere(); Console::WriteLine(ints2[0]);

// compiler error: gcroot does not support [] operation

To solve this problem, you can convert the gcroot variable to the type of the wrapped tracking handle, as shown in the following code:

gcroot<List<int>A> ints2 = GetIntListFromSomewhere(); List<int>A ints3 = ints2;

Console::WriteLine(ints3[0]); // this option is legal

This conversion is possible because gcroot implements an appropriate conversion operator. There is an inconsistency between gcroot and auto_gcroot in that auto_gcroot does not support a conversion to the wrapped tracking handle type. To obtain the wrapped tracking handle from an auto_gcroot variable, you have to call the member function get:

auto_gcroot<List<int>A> ints2 = GetIntListFromSomewhere(); List<int>A ints3 = ints2.get(); Console::WriteLine(ints3[0]);

To find out whether a gcroot or an auto_gcroot variable actually refers to a managed object or just contains a nullptr reference, you can use the following expression:

or its positive variant: if (ints2)

However, it is not possible to achieve the same by writing the following: if (ints2 == nullptr)

Unfortunately, you may face an additional pitfall if you use auto_gcroot. Currently, auto_gcroot has an unintended conversion to StringA. This can cause the following undesired behavior:

auto_gcroot<FileSystemWatcherA> fsw = gcnew FileSystemWatcher(); fl(fsw);

// this line should not compile, because neither an auto_gcroot, nor a

// FileSystemWatcher should be convertible to a StringA, but it does compile

Was this article helpful?

0 0

Post a comment