Home  >  Article  >  Backend Development  >  Memory allocation method for C++ function pointer parameters

Memory allocation method for C++ function pointer parameters

WBOY
WBOYOriginal
2024-04-20 21:09:02983browse

C function pointer parameters can use two memory allocation methods: dynamic allocation or static allocation. Dynamic allocation uses heap memory, allocating and releasing memory at runtime; static allocation uses stack memory, and allocates memory at compile time.

C++ 函数指针参数的内存分配方式

C Memory allocation method for function pointer parameters

Function pointer is a powerful tool in C that allows us to treat functions as first-class citizens . This means we can pass function pointers to other functions, store them in data structures, or even create them dynamically.

When using function pointers as parameters, we need to consider the memory allocation method. There are two main methods:

1. Dynamic allocation

If we are not sure of the specific type of the function pointer, or want to change the value of the function pointer at runtime, we can use dynamic allocation. Dynamic allocation uses heap memory, for example:

// 创建一个指向函数的指针
int (*func_ptr)(int);

// 动态分配函数指针指向的内存
func_ptr = new int(*)(int)([](int x) { return x * x; });

// 调用函数指针
int result = func_ptr(5);

2. Static allocation

If we know exactly the type of the function pointer and do not intend to change its value at runtime, we can use static distribute. Static allocation uses stack memory, for example:

// 创建一个指向函数的指针
int (*func_ptr)(int) = [](int x) { return x * x; };

// 调用函数指针
int result = func_ptr(5);

Practical case

Suppose we have a class named Shape, which has two derived classes: Circle and Square. Each derived class has a calcArea method to calculate its area. We can generically calculate the area of ​​any shape using a function pointer argument as follows:

class Shape {
public:
    virtual double calcArea() = 0;
};

class Circle : public Shape {
public:
    double calcArea() override { return 3.14; }
};

class Square : public Shape {
public:
    double calcArea() override { return 4.0; }
};

// 函数指针参数表示计算形状面积的函数
double calcArea(Shape *shape, double (*func_ptr)(Shape*)) {
    return func_ptr(shape);
}

int main() {
    Circle circle;
    Square square;

    // 通过函数指针动态地计算面积
    double circleArea = calcArea(&circle, [](Shape *shape) { return static_cast<Circle*>(shape)->calcArea(); });
    double squareArea = calcArea(&square, [](Shape *shape) { return static_cast<Square*>(shape)->calcArea(); });
}

The above is the detailed content of Memory allocation method for C++ function pointer parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn