惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
量子位
G
Google Developers Blog
J
Java Code Geeks
N
Netflix TechBlog - Medium
博客园 - 聂微东
宝玉的分享
宝玉的分享
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
The Cloudflare Blog
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
雷峰网
雷峰网
M
MIT News - Artificial intelligence
T
Tailwind CSS Blog
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
博客园 - 三生石上(FineUI控件)
Microsoft Azure Blog
Microsoft Azure Blog
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss

The Old New Thing

std::call_once vs. std::async - The Old New Thing Magic statics vs. std::call_once - The Old New Thing Why do Microsoft job levels start in the high 50's instead of starting at a sane number like 1? - The Old New Thing Why didn't Read­Directory­ChangesW provide a way to correlate the two sides of a rename operation? - The Old New Thing How can I remove the Close button from my window caption? - The Old New Thing Why is the x86 undefined instruction called ud2? Why 2? - The Old New Thing What algorithm did Windows XP use to choose your initial user picture? - The Old New Thing A sample use of the winstart.bat file in Windows 95 - The Old New Thing Why don't we allow stacks to be sparse, instead of forcing them to be contiguous? - The Old New Thing What happens if you change a window class's GCL_CB­WND­EXTRA? - The Old New Thing The case of the progress callback that never got called when progress happened - The Old New Thing The perils of binding to value types in XAML - The Old New Thing Microspeak: Funded / unfunded - The Old New Thing AWE does not require PAE, though PAE makes it much more useful - The Old New Thing On forcing all derived classes to implement a specific non-virtual method, part 2 - The Old New Thing On forcing all derived classes to implement a specific non-virtual method, part 1 - The Old New Thing In the product end game, every change carries significant risk, episode 2 - The Old New Thing Why didn't the Windows Entertainment Pack just run the MS-DOS version inside an emulator? - The Old New Thing Comparing the two holograms on the Windows 95 box - The Old New Thing Reducing C++ template bloat by factoring out the type-dependent portions of the function, practical exam - The Old New Thing Reducing C++ template bloat by factoring out the type-dependent portions of the function - The Old New Thing On wrapping a callable in a lambda that just calls it with the same parameters - The Old New Thing Why did the Microsoft Entertainment Pack for Windows have a special sticker announcing that it also had Tetris? - The Old New Thing How do functions like alloca allocate memory from the stack? - The Old New Thing How do functions like alloca allocate memory from the stack? - The Old New Thing Forcing an ARM64X executable to run as a specific architecture - The Old New Thing A little helper class for managing LPPROC_THREAD_ATTRIBUTE_LISTs - The Old New Thing The comments that go into code versus those that go into the pull request description - The Old New Thing The little-known winstart.bat batch file - The Old New Thing How can I perform a Copy­File&shy in unbuffered mode? - The Old New Thing
Creating a fake agile wrapper that is technically agile b...
Raymond Chen · 2026-08-07 · via The Old New Thing

Last time, I confessed that I lied when i said that we can’t use std::unique_ptr to manage the registration cookie.

The trick here is that the registration cookie is of type DWORD, which fits in a pointer, so we can smuggle the integer value inside a pointer.

template<typename T>
struct fake_agile_ref
{
private:
    using Smart = std::conditional_t<
        std::is_base_of_v<winrt::Windows::Foundation::IUnknown, T>,
        T, winrt::com_ptr<T>>;

    struct git_deleter                                                                           
    {                                                                                            
        winrt::com_ptr<IGlobalInterfaceTable> m_git;                                             
                                                                                                 
        void operator()(void* p)                                                                 
        {                                                                                        
            m_git->RevokeInterfaceFromGlobal(static_cast<DWORD>(reinterpret_cast<uintptr_t>(p)));
        }                                                                                        
    };                                                                                           

    winrt::com_ptr<IContextCallback> m_context;
    ULONG_PTR m_token = 0;
    std::unique_ptr<void, git_deleter> m_cookie;
    void* m_raw = nullptr;

Our custom deleter holds a pointer to the Global Interface Table and uses it to revoke the cookie on destruction. The cookie is an integer smuggled inside a pointer, so we cast the pointer back to an integer by passing through a uintptr_t to avoid a compiler warning about casting between an integer and pointer of different sizes.

We are relying on the fact that Windows implementations are required to support round-tripping integers through pointers. Macros like MAKEINTRESOURCE rely on it. It’s also codified in Windows with helper functions like PtrToInt and IntToPtr, but I’m writing it out for expository purposes rather than using those helpers.

We can then store the Global Interface Table pointer and the corresponding cookie in the unique_ptr:

    fake_agile_ref(Smart const& p) : m_raw(winrt::get_abi(p))
    {
        if (m_raw) {
            m_context = winrt::capture<IContextCallback>(CoGetObjectContext);
            m_token = get_context_token();
            auto& git = m_cookie.get_deleter().m_git;                                          
            git = winrt::create_instance<IGlobalInterfaceTable>(CLSID_StdGlobalInterfaceTable);
            DWORD cookie;                                                                      
            winrt::check_hresult(git->RegisterInterfaceInGlobal(
                winrt::make<force_marshal<Smart>>(p).get(),
                __uuidof(IUnknown), &m_cookie));
            m_cookie.reset(reinterpret_cast<void*>(static_cast<uintptr_t>(cookie)));
        }
    }

And now that we are letting unique_ptr manage the lifetime of the cookie, we don’t need a custom destructor, which allows us to use the Rule of Zero and simply not have any copy or move constructors or assignment operators.

    // fake_agile_ref(fake_agile_ref&& other) noexcept :
    //     m_context(std::move(other.m_context)),
    //     m_token(std:exchange(other.m_token, 0)),
    //     m_git(std::move(other.m_git)),
    //     m_cookie(std::exchange(other.m_cookie, 0)),
    //     m_raw(other.m_raw)
    // {
    // }

    // fake_agile_ref& operator=(fake_agile_ref&& other) noexcept
    // {
    //     using std::swap;
    //     swap(m_context, other.m_context);
    //     swap(m_token, other.m_token);
    //     swap(m_git, other.m_git);
    //     swap(m_cookie, other.m_cookie);
    //     swap(m_raw, other.m_raw);
    // }

    // ~fake_agile_ref()
    // {
    //     if (m_cookie) {
    //        m_git->RevokeInterfaceFromGlobal(std::exchange(m_cookie, 0));
    //    }
    // }

Since we are storing the cookie in a unique_ptr, we need to adjust the empty method:

    bool empty() const noexcept
    {
        return reinterpret_cast<uintptr_t>(m_cookie.get()) != 0;
    }

Bonus chatter: The Windows Implementation Library (wil) has a class similar to unique_ptr called wil::unique_any that lets you apply cleanup to any data type, not just a pointer.

Category

Topics

Author

Raymond Chen

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.