1. Function pointer definition
In C++, the way function pointers are defined depends on the signature (parameter type and return type) of the function pointed to.
Here are some examples:
-
Function pointers without parameters and return values:
// Define function pointer typetypedef void (*FunctionPointer)(); // Use type definition to declare function pointer variableFunctionPointer myFunctionPointer;
-
Function pointer with parameters:
// Define the function pointer type, here assuming that the function accepts an integer parameter and returns an integertypedef int (*FunctionPointerWithParam)(int); // Use type definition to declare function pointer variableFunctionPointerWithParam myFunctionPointer;
-
Function pointer with multiple parameters:
// Define the function pointer type, here assuming that the function accepts two integer parameters and returns a floating point numbertypedef float (*FunctionPointerWithMultipleParams)(int, int); // Use type definition to declare function pointer variableFunctionPointerWithMultipleParams myFunctionPointer;
-
More complex function signatures:
// Define the function pointer type, here assuming that the function accepts a string parameter and an integer parameter, and returns a Boolean valuetypedef bool (*ComplexFunctionPointer)(const char*, int); // Use type definition to declare function pointer variableComplexFunctionPointer myFunctionPointer;
In C++11 and later, you can also useusing
Keywords to define function pointer types, as follows:
// Use the using keyword to define function pointer types without parameters and return valuesusing FunctionPointer = void(*)(); // Use type definition to declare function pointer variableFunctionPointer myFunctionPointer;
Whether it is usedtypedef
stillusing
, are all for convenient definition of more readable function pointer types. Choosing the right way to define depends on the individual or team's coding style and preferences.
2. Use of function pointers
The use of function pointers involves two main steps: defining function pointers and calling functions using function pointers.
Here is a simple example that demonstrates how to use function pointers:
#include <iostream> // Suppose there is a function that takes two integer parameters and returns their sumint add(int a, int b) { return a + b; } int main() { // Define function pointer type typedef int (*AddFunction)(int, int); // Create a function pointer and point it to the corresponding function AddFunction myFunctionPointer = add; // Call function using function pointer int result = myFunctionPointer(3, 4); // Output result std::cout << "Result: " << result << std::endl; return 0; }
In the above example, we first define a functionadd
, accepts two integer arguments and returns their sum. Next, we define a function pointer typeAddFunction
, this type points to the signature of the function. Then, we created a function pointermyFunctionPointer
and point it to the functionadd
. Finally, by calling the function pointer, we called the functionadd
And output the result.
It is worth noting that when using function pointers, make sure that the type of function pointer and the signature of the called function are consistent to avoid the problem of type mismatch.
In modern C++, it can be usedauto
Keywords to simplify the declaration of function pointers, as follows:
#include <iostream> int add(int a, int b) { return a + b; } int main() { // Use auto to simplify the declaration of function pointer auto myFunctionPointer = add; // Call function using function pointer int result = myFunctionPointer(3, 4); // Output result std::cout << "Result: " << result << std::endl; return 0; }
In this example, the compiler will automatically deduce the type of function pointer.
3. Pointer function
In C++, a pointer function refers to a function returning a value of a pointer type. This function is usually used for dynamic memory allocation, or to return addresses of static or global variables. The use of pointer functions requires the #include header file.
The following are some basic concepts and usages of pointer functions:
Function that returns a pointer
int* function() { int value = 42; return &value; // Return the address of the local variable, which is dangerous, because the local variable will be destroyed after the function returns}
In the above example, function returns a pointer to type int. However, this example is unsafe because it returns the address of the local variable value. Once the function is executed, the memory space of the value will be released, and the returned pointer points to an undefined value, which is called "hanging pointer".
Returns a pointer to a static variable
To avoid the above problems, you can use static variables:
int* function() { static int value = 42; return &value; // Return the address of the static variable}
Static variables are initialized when the function is called for the first time and retain their value throughout the run of the program.
Returns a dynamically allocated pointer
Safer dynamic memory allocation
int* function() { int* value = new int(42); // Dynamically allocate memory return value; // Returns the dynamically allocated memory address}
In this case, you should use the delete operator at appropriate times to free up memory to avoid memory leakage.
Returns the pointer to the array
Functions can also return pointers to arrays:
int* function(int size) { static int array[size]; // VLA (Variable Length Array), C99 standard for (int i = 0; i < size; ++i) { array[i] = i; } return array; // Return the pointer to the array}
Pointer parameters and pointer return value
Functions can accept pointer parameters and return pointers at the same time
int* function(int* ptr) { if (ptr) { return ptr; // Return the incoming pointer } return nullptr; // If the passed in is nullptr, return nullptr}
Things to note
When returning the address of a local variable, make sure that the life cycle of the local variable is longer than the period when using the address.
Dynamically allocated memory needs to be freed.
When returning the address of a static or global variable, ensure thread safety (if the program is multi-threaded).
When returning pointers to an array, make sure the caller knows the size of the array to avoid out-of-bounds access.
This is the end of this article about the implementation of C++ function pointers. For more related C++ function pointers, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!