What is a handle in C++?
Asked Answered
S

9

116

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?

Sleepless answered 19/8, 2009 at 23:13 Comment(2)
en.wikipedia.org/wiki/Handle_%28computing%29Finfoot
Look into the Chain of Responsibility pattern, you'll learn that a "Handle" is a basically a node, and that a "Handler" is a small set of them. The "magic" comes from recursionImminent
H
113

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++.

Hollands answered 19/8, 2009 at 23:17 Comment(4)
A Handle can be useful for saving states (among others). If u have data in a structure like an std::vector. Your object may be at different memory locations at different times during execution of a program, which means your pointer to that memory will change values. With a handle it never changes, it always references your object. Imagine saving a state of a program (like in a game) - you wouldn't save out a pointer location to data and later import the data again and try to get that address in memory. You can however save out a Handle with your data, and import the data and handle.Politician
Is it possible to convert a HANDLE into an equivalent in Linux? I have to migrate a program that uses HANDLE from Windows to Linux.Penthea
That is the correct answer, that they can be anything, and that the code that uses them defines the type of the handle. I tried to make a more concise version of my own similar answer, couldn't help myself, for posterity. @CornelVerster - They are the same in linux. I mean, not OS handles, but the concept. So, it depends on the handle as to its migration, or even need to migrate.Aeromechanic
@Matthew Iselin: in any API documentation, do they define that thing is a handler then we should know to pass them to functions, otherwise how we can know what is a handler in API documentationSura
M
65

A handle is a pointer or index with no visible type attached to it. Usually you see something like:

 typedef void* HANDLE;
 HANDLE myHandleToSomething = CreateSomething();

So in your code you just pass HANDLE around as an opaque value.

In the code that uses the object, it casts the pointer to a real structure type and uses it:

 int doSomething(HANDLE s, int a, int b) {
     Something* something = reinterpret_cast<Something*>(s);
     return something->doit(a, b);
 }

Or it uses it as an index to an array/vector:

 int doSomething(HANDLE s, int a, int b) {
     int index = (int)s;
     try {
         Something& something = vecSomething[index];
         return something.doit(a, b);
     } catch (boundscheck& e) {
         throw SomethingException(INVALID_HANDLE);
     }
 }
Morse answered 19/8, 2009 at 23:30 Comment(0)
M
35

A handle is a sort of pointer in that it is typically a way of referencing some entity.

It would be more accurate to say that a pointer is one type of handle, but not all handles are pointers.

For example, a handle may also be some index into an in memory table, which corresponds to an entry that itself contains a pointer to some object.

The key thing is that when you have a "handle", you neither know nor care how that handle actually ends up identifying the thing that it identifies, all you need to know is that it does.

It should also be obvious that there is no single answer to "what exactly is a handle", because handles to different things, even in the same system, may be implemented in different ways "under the hood". But you shouldn't need to be concerned with those differences.

Mewl answered 19/8, 2009 at 23:20 Comment(1)
Right! A handle is, in essence, an abstract pointer, in the sense that a pointer is usually defined as 'a special variable which points to the memory address of a resource', while a handle, even though it references a resource, it does not necessarily point to its memory address (but can be implemented as, say, a simple array index to an internal representation which is opaque to the user).Packing
C
8

In C++/CLI, a handle is a pointer to an object located on the GC heap. Creating an object on the (unmanaged) C++ heap is achieved using new and the result of a new expression is a "normal" pointer. A managed object is allocated on the GC (managed) heap with a gcnew expression. The result will be a handle. You can't do pointer arithmetic on handles. You don't free handles. The GC will take care of them. Also, the GC is free to relocate objects on the managed heap and update the handles to point to the new locations while the program is running.

Coltun answered 19/8, 2009 at 23:17 Comment(0)
C
5

This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".

It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.

Chace answered 19/8, 2009 at 23:18 Comment(0)
S
3

Pointer is a special case of handle. The benefit of a pointer is that it identifies an object directly in memory, for the price of the object becoming non-relocatable. Handles abstract the location of an object in memory away, but require additional context to access it. For example, with handle defined as an array index, we need an array base pointer to calculate the address of an item. Sometimes the context is implicit at call site, e.g. when the object pool is global. That allows optimizing the size of a handle and use, e.g. 16-bit int instead of a 64-bit pointer.

Selfemployed answered 27/5, 2021 at 12:43 Comment(1)
Actually, I like your answer best :) even though I might disagree about the benefit of a pointer — then again, I'm spoiled by having been too far away from C/C++ and explicit memory allocation, and spending too much time with automatic garbage-collected programming languages, where so-called 'pointers' may be much more abstract than in C/C++...Packing
N
2

HANDLE hnd; is the same as void * ptr;

HANDLE is a typedef defined in the winnt.h file in Visual Studio (Windows):

typedef void *HANDLE;

Read more about HANDLE

Navigation answered 19/1, 2016 at 7:8 Comment(1)
That only applies to Windows, and only one of many types of handles used through the Windows architecture. However, that is what would be known as a 'normal Windows application-level handle'.Aeromechanic
A
2

A handle is whatever you want it to be.

A handle can be a unsigned integer used in some lookup table.

A handle can be a pointer to, or into, a larger set of data.

It depends on how the code that uses the handle behaves. That determines the handle type.

The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.

Aeromechanic answered 24/9, 2017 at 22:27 Comment(1)
... without, however, letting the programmer know how it's implemented (as opposed to a pointer, where the representation — while trivial — is obvious: a pointer points to the memory address of a resource, while a handle can be anything)Packing
F
-1

What is was taught way back it that a handle is a pointer to a pointer. Useful not only for objects but also pure data loaded into memory.

The big advantage with handles is that is easier lets you shuffle and move data or objects being used by other handles. (think "defragmenting RAM") Only the memory-area of the handles needs to be un-moved (but updated).

Finch answered 27/2 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.