What is a handle in C++?

Xenoprimate picture Xenoprimate · Aug 20, 2009 · Viewed 193.1k times · Source

I have been told that a handle is sort of a pointer, but not, and that it allows you to keep a reference to an object, rather than the object itself. What is a more elaborate explanation?

Answer

Matthew Iselin picture Matthew Iselin · Aug 20, 2009

A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.

For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).

EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.