1

I have to modify an existing Control using the Loaded event from a static member function that has to:

  1. Not storing the revoker into some class member because the code is inside a static function. Also, I don't want to store it somewhere else globally.

  2. The Loaded callback should only be called once, so it needs to revoke itself.

Currently this is my solution

        auto loadedRevoker = new winrt::Microsoft::UI::Xaml::Controls::CommandBar::Loaded_revoker;
        *loadedRevoker = commandBar.Loaded(winrt::auto_revoke, [loadedRevoker](auto&& self, auto&&) {
            //revoke event
            loadedRevoker->revoke();
            delete loadedRevoker;

            //do something
        });

It works, but I want to change it into using smart pointers and couldn't figure out a correct way.

1 Answer 1

1

As you did not provide MRE (ie something whch I could compile) my answer was not tested:

It works, but I want to change it into using smart pointers and couldn't figure out a correct way.

auto revoker = std::make_shared<winrt::Microsoft::UI::Xaml::Controls::CommandBar::Loaded_revoker>();

*revoker = commandBar.Loaded(
    winrt::auto_revoke,
    [revoker](auto&& /*sender*/, auto&& /*args*/)
    {
        // revoke event once, then let shared_ptr go out of scope
        revoker->revoke();

        // do something
    });

or

auto revoker_up = std::make_unique<winrt::Microsoft::UI::Xaml::Controls::CommandBar::Loaded_revoker>();

*revoker_up = commandBar.Loaded(
    winrt::auto_revoke,
    [rev = revoker_up.get(), keep = std::move(revoker_up)](auto&& /*sender*/, auto&& /*args*/)
    {
        rev->revoke();
        // do something
        // keep is destroyed when handler scope ends
    });
Sign up to request clarification or add additional context in comments.

1 Comment

I added a noisy class that prints out constructor and destructor calls with a shared_ptr in the capture, and the first method seems to work. Curiously the destructor prints after the callback finishes, not on the line revoke.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.