Acorn
Acorn

Reputation: 26186

In what context one may need to dynamically allocate pointers to functions?

Coming from a comment from @Ayxan to this answer on Is delete *p an alternative to delete [] p?, with the example:

int (**p) () = new (int (*[7]) ());
delete [] p;

Upvotes: 2

Views: 77

Answers (1)

Acorn
Acorn

Reputation: 26186

For instance, you may want to have a list of arbitrary operations to execute (which you do not know at compile-time):

using Op = void (*)();

static void run(Op * ops, int n)
{
    for (int i = 0; i < n; ++i)
        ops[i]();
}

void foo();
void bar();

void g()
{
    constexpr int n = 3;
    Op * ops = new Op[n];

    ops[0] = foo;
    ops[1] = bar;
    ops[2] = foo;

    run(ops, n);

    delete [] ops;
}

Of course, in C++, you would normally keep this in a container and use function objects too, but this is for the sake of the original question.

Upvotes: 4

Related Questions