windows 如果我调用 GlobalLock(),然后调用 GlobalUnlock() 失败,会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2160850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:50:20  来源:igfitidea点击:

What happens if I call GlobalLock(), then fail to call GlobalUnlock()?

windowswinapivisual-c++memory-management

提问by sharptooth

In Win32 in order to paste data into the clipboard I have to call GlobalAlloc(), then GlobalLock()to obtain a pointer, then copy data, then call GlobalUnlock()and SetClipboardData().

在 Win32 中,为了将数据粘贴到剪贴板中,我必须调用GlobalAlloc(),然后GlobalLock()获取指针,然后复制数据,然后调用GlobalUnlock()SetClipboardData()

If the code is in C++ an exception might be thrown between calls to GlobalLock()and GlobalUnlock()and if I don't take care of this GlobalUnlock()will not be called.

如果代码是在 C++ 中,则可能会在对GlobalLock()和 的调用之间引发异常GlobalUnlock(),如果我不注意这GlobalUnlock()将不会被调用。

It this a problem? What exactly happens if I call GlobalLock()and for whatever reason skip a pairing GlobalUnlock()call?

这是一个问题吗?如果我打电话GlobalLock()并出于任何原因跳过配对GlobalUnlock()电话,究竟会发生什么?

回答by Michael Burr

More than you ever wanted to know (really) about GlobalLock(), courtesy of Raymond Chen:

比你想知道的更多(真的)GlobalLock(),由 Raymond Chen 提供:

I'm marking this community wiki because I actually don't know if these articles answer your question. But they're probably worth wading through, at least for a skim.

我标记这个社区维基是因为我实际上不知道这些文章是否回答了您的问题。但它们可能值得一试,至少可以略读一下。

But one way to handle your problem of dealing with the GlobalUnlock() in the face of exceptions is to use an RAII class to manage the GlobalLock()/GlobalUnlock()calls.

但是,在遇到异常时处理 GlobalUnlock() 问题的一种方法是使用 RAII 类来管理GlobalLock()/GlobalUnlock()调用。

回答by RED SOFT ADAIR

The Question is not only about if or if not you call GlobalUnlock(). You must call GlobalUnlock()and GlobalFree(). Both must be called in order to release the memory you allocated:

问题不仅仅是关于你是否打电话GlobalUnlock()。您必须调用GlobalUnlock()GlobalFree()。两者都必须被调用才能释放你分配的内存:

HGLOBAL hdl = NULL;
void *ptr = NULL

  try {
    hdl = GlobalAlloc();
    ptr = GlobalLock(hdl);

    // etc...
    GlobalUnlock(hdl);
    ptr = NULL;
    SetClipboardData(..., hdl );
  }
  catch (...) {
    if(ptr)
        GlobalUnlock(hdl);
    if(hdl)
        GlobalFree(hdl);
    throw;
  }

The leak would be application wide. When you exit a windows application, all allocated private memory is released automatically

泄漏将应用广泛。当您退出 Windows 应用程序时,所有分配的私有内存都会自动释放