February 11th, 2021

The COM static store, part 4: Aggregating into a single object

So far, we’ve been looking at how you can use the COM static store to hold a singleton which will be run down when COM uninitializes. But what if you have a lot of things you want to save? I mean, you could put each one individually in the COM static store, but that gets quite cumbersome. And some of the things might not even be COM objects, or they may be COM objects that do not support IInspectable. What can you do about those?

You can wrap all of your global state into a single object that supports IInspectable, and put that single object into the COM static store. That way, you can just grab one thing out of the COM static store instead of having to go back to the COM static store for each one.

// C++/WinRT
struct SharedState :
    winrt::implements<SharedState,
                      winrt::Windows::Foundation::IInspectable>
{
    int some_value = 0;
    winrt::com_ptr<IStream> stream;
    std::vector<winrt::com_ptr<IStorage>> storages;
};

winrt::com_ptr<SharedState>
GetSingletonSharedState()
{
    auto props = CoreApplication::Properties();
    if (auto found = props.TryLookup(L"SharedState")) {
        return as_self<SharedState>(found);
    }
    auto value = winrt::make_self<SharedState>();
    static winrt::slim_mutex lock;
    winrt::slim_lock_guard const guard{ lock };
    if (auto found = props.TryLookup(L"SharedState")) {
        return as_self<SharedState>(found);
    }
    props.Insert(name, *value);
    return value;
}

Now, when you need stuff, you can ask for the singleton SharedState and access everything, rather than having to get each one individually.

But wait, we can do even better still.

Next time.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.