Dynamically allocated array of function pointers

Hello, I would like to know if this code is correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

int say_one(const std::string &s)
{
    std::clog << s << ": One!\n";
    return 1;
}

int say_two(const std::string &s)
{
    std::clog << s << ": Two!\n";
    return 2;
}

int main()
{
    int (**p)(const std::string &) = new (int(*[2])(const std::string &));

    p[0] = &say_one;
    p[1] = &say_two;
    p[0]("Anthony");
    p[1]("Richard");
    delete[] p;
}
closed account (S6k9GNh0)
No, don't dynamically allocate STL containers. Incorrectly read code. Still very strange.

EDIT: Also, that allocation line is so awkward, it's wrong just by count of awkwardness.
Last edited on
valgrind is happy with it, and so are gcc, clang, Sun and IBM compilers.
Thanks Cubbi for testing. I asked this question because that [2] seems very awkwardly placed to me.
yes, abstract-declarator is an awkward piece of grammar.. which is why people like typedefs and type aliases so much.
I don't see how the [2] is the confusing part. It may not be immediately obvious, because pointers to pointers suck, but you're telling it to allocate an array of two pointers. This doesn't look awkward does it?
int** ptrtoptr= new int*[2] If anything all of the extra braces making them into function pointers are what make your eyes want to cross over.
It's just that people are used to seeing the square brackets on the right, as in new SomeComplexType[2];, instead of deep inside the declarator. The ones on the right might not have much to do with it at all:

1
2
    auto p = new (int (*(*[2])())[3]); // array of two pointers
    delete[] p;


I am not proud of being able to write this.
Last edited on
What's awkward is function pointer syntax in conjunction with new[].
Topic archived. No new replies allowed.