dalle dalle - 7 months ago 59
C++ Question

Does C++/CX detect and solve cycles of objects?

From my understanding C++/CX doesn't use garbage collection, it use a reference counted approach instead.

The problem with reference counting is that it cannot dispose of cycles. Cycles are usually solved using weak references, such as weak_ptr in standard C++.

But I cannot find a way in C++/CX to explicitly specify a weak reference. From that I would assume that this is handled by C++/CX itself. I am wondering how C++/CX would solve this.

For instance, look at the following code:

ref class Foo
Bar^ bar;

ref class Bar
Foo^ foo;

ref class App
virtual void OnLaunched(LaunchActivatedEventArgs^ args)
Foo^ foo = ref new Foo();
Bar^ bar = ref new Bar();
foo.bar = bar;
bar.foo = foo;

How does C++/CX detect this cycle?

How does C++/CX solve this cycle?

How does C++/CX decide which one of these objects should be the "root object" and which one should be the "weak reference"?


Short answer: No, C++/CX doesn't detect and solve cycles of objects.

Long answer: WinRT itself has a standard mechanism for weak references. On ABI level, this is defined in terms of interfaces IWeakReference and IWeakReferenceSource, which you can see in "%ProgramFiles%\Windows Kits\8.0\Include\winrt\WeakReference.idl".

In C++/CX, all your classes will automatically implement IWeakReferenceSource, and hence all their instances can be weakly referenced. To obtain and store a weak reference to an object, you should use the helper class Platform::WeakReference (defined in vccorlib.h):

Foo^ foo = ref new Foo;
Platform::WeakReference weakRef(foo);

to retrieve back the object, use Resolve<T>:

foo = weakRef.Resolve<Foo>();

As usual, you will get nullptr is the object has already been destroyed.

Other than that, an instance of WeakReference behaves more or less like a smart pointer - it's copyable, movable, comparable, assignable from nullptr, has an implicit conversion to an unspecified bool type etc.

Note that, as of VS11 Beta, IDE Intellisense will balk at WeakReference if you try to use it, underlining it with squiggles etc. The compiler can handle them just fine despite all that, though.