c++ void* explanation

In pointer operations, void* is a commonly used pointer, also known as a typeless pointer, which can be considered as an abstraction of the pointer type.

untyped pointer properties

The void pointer can accept all typed pointer assignments

    float obj = 1.2;
    float* pobj = &obj;
    void* pv = &obj;    //void指针可以指向任意类型的变量
    pv = pobj;          //void指针可以被任意类型的指针赋值

Casting is required for void pointer assignment

float* pf = (float*)pv;

The void pointer records the location of the memory, but what type of object is stored in this block of memory and how many bytes the object occupies in total are unknown.

Therefore, if you want to use a void pointer for assignment, you must first perform a forced type conversion and define the object stored in the memory before you can use it.

Void pointers can compare addresses with other types of pointers

std::cout<<(pv == pobj)<<std::endl;

Although it is not necessarily known what type of object the void pointer points to, the address stored inside it actually exists, so it can be compared with the addresses stored by other pointers.

Use of untyped pointers

It can be seen from the properties that the void pointer can accept the assignment of all types of pointers, and can be assigned to other types of pointers through forced conversion. It has considerable flexibility, so it is often used in function parameters and return values, so when writing functions There is no need to provide processing solutions for various pointers.

Guess you like

Origin blog.csdn.net/m0_37872216/article/details/126886155