问题描述
在Win32中,为了将数据粘贴到剪贴板中,我必须调用GlobalAlloc()
,然后调用 GlobalLock()
获取指针,然后复制数据,然后调用GlobalUnlock()
和SetClipboardData()
.
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()
.
如果代码是C ++,则在调用GlobalLock()
和GlobalUnlock()
之间可能会引发异常,并且如果我不注意,则不会调用GlobalUnlock()
.
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.
这是一个问题吗?如果我拨打GlobalLock()
并出于任何原因跳过配对GlobalUnlock()
通话,究竟会发生什么?
It this a problem? What exactly happens if I call GlobalLock()
and for whatever reason skip a pairing GlobalUnlock()
call?
推荐答案
问题不仅与是否呼叫GlobalUnlock()
有关.您必须调用GlobalUnlock()
和GlobalFree()
.必须同时调用这两个函数才能释放您分配的内存:
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:
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;
}
泄漏将在整个应用程序范围内发生.当您退出Windows应用程序时,所有分配的私有内存都会自动释放
The leak would be application wide. When you exit a windows application, all allocated private memory is released automatically
这篇关于如果我调用GlobalLock()而不调用GlobalUnlock()会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!