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
{
public:
Bar^ bar;
};
ref class Bar
{
public:
Foo^ foo;
};
ref class App
{
public:
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
IWeakReferenceandIWeakReferenceSource, 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 classPlatform::WeakReference(defined in vccorlib.h):to retrieve back the object, use
Resolve<T>:As usual, you will get
nullptris the object has already been destroyed.Other than that, an instance of
WeakReferencebehaves more or less like a smart pointer – it’s copyable, movable, comparable, assignable fromnullptr, has an implicit conversion to an unspecified bool type etc.Note that, as of VS11 Beta, IDE Intellisense will balk at
WeakReferenceif you try to use it, underlining it with squiggles etc. The compiler can handle them just fine despite all that, though.