when to use void* in c++

前端 未结 2 441
予麋鹿
予麋鹿 2021-01-04 20:57

I am trying to wrap my head about a void* and what is appropriate use of it and if there is any potentially abusive use I should know about. (Meaning something

相关标签:
2条回答
  • 2021-01-04 21:25

    void* is a memory address without a type. It's useful when the code around it has some other way of knowing what type it is working with (for example, memchr needs to have the size of the memory area passed in addition to the address).

    0 讨论(0)
  • 2021-01-04 21:26

    In C it's fairly common to use void * to create a generic collection. For example, if you wanted a generic linked list, you might write something like:

    typedef struct node  { 
        void *data;
        struct node *next;
    } node;
    

    Then you could create one linked list of foo, another linked list of bar, and so on.

    In C++, however, this is rarely useful. In a typical case, you'd want to write equivalent code as a template instead:

    template <typename T>
    class node { 
         T data;
         node *next;
    };
    

    With older compilers, you could reduce the generated code by combining the two techniques. In this case, you'd use a collection of pointers to void to store the data, then have a template front-end that just handled casting T * to void * when you stored the data, and back from void * to T * when you retrieved the data.

    Improvements in compilers/linkers have rendered this technique (almost?) entirely obsolete though. Older compilers would generate separate code for each type over which you instantiated your template, even where the instantiation type was irrelevant. Current compilers (or toolchains, anyway -- quite a bit of this is really handled by the linker) identify the identical code sequences, and merge them together automatically.

    Bottom line: unless you need C compatibility, or you're writing a replacement operator new/operator delete, use of void * in well written C++ is usually pretty rare.

    0 讨论(0)
提交回复
热议问题