What is a handle in C++?

后端 未结 7 1192
眼角桃花
眼角桃花 2020-11-29 16:55

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 elaborat

7条回答
  •  萌比男神i
    2020-11-29 17:38

    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(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);
         }
     }
    

提交回复
热议问题