Winui 3 winrt C++ reference counting

Viewed 77

Using WinUI 3, Winrt C++ in the following code:
Is myRectangle reference counted? Or is it copied?

namespace winrt::MyProject::implementation{

void MyProjectClass::fnc(){

winrt::Microsoft::UI::Xaml::Controls::Canvas myCanvas = CanvasElementFromXAML();
winrt::Microsoft::UI::Xaml::Shapes::Rectangle myRectangle;
myCanvas.Children.Append(myRectangle);

}
}

I see this type of code in examples. In C++ (without MS extensions) this would lead to a dangling reference/pointer if not copied, since myRectangle is a local var which will go out of scope. myCanvas.Children.Append() receives UIElement const& value
void Append(UIElement const& value)

here the const reference would communicate that the argument cannot be changed, therefore ref count cannot be modified.

1 Answers

WinRT is COM-based, so the Canvas instance and the Rectangle instance are both COM-objects.

So, Append implementation will call AddRef on myRectangle. In this case, there's no specific MS extension involved.

Related