Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it illegal to define a pointer to pointer variable with constructor invocation notation?

Tags:

c++

When I'm using constructor invocation notation (declare-)defining a pointer to pointer (instead of assignment notation - of course that will do the same thing at runtime; it's just a convention), I get a compiler error. I was wondering why this is.

struct  Foo 
{ /* ... */ };

int main(int argc, char** argv)
{
  Foo*  parFoo = new Foo[2];
  Foo** ppFoo(&parFoo); // invalid: C2059
  Foo** ppFoo = &parFoo; // OK

  delete[] parFoo;
}

The error is a C2059 - invalid token, which doesn't say a lot. However, the & isn't the problem (meaning that it's probably not an operator precedence error). If I do the following:

int main(int argc, char** argv)
{
  Foo*  parFoo = new Foo[2];
  Foo** ppFoo = &parFoo; // OK
  Foo** ppFoo2(ppFoo); // invalid: C2061

  delete[] parFoo;
}

...then I get a C2061, meaning that this time it's the ppFoo identifier that's in the wrong place.

What syntactical rule causes this, i.e. why can't the constructor invocation notation be used to define pointers to pointers, only "less degree pointed to" types?

like image 892
zyndor Avatar asked Dec 10 '12 18:12

zyndor


1 Answers

It looks like valid C++. And, as others pointed out, GCC does accept it. As per compiler error you get, it looks like a bug in MSVC's parser.

In fact adding parentheses helps it to parse the code correctly:

Foo*  parFoo = new Foo[2];
Foo (**ppFoo2)(&parFoo); // compiles in MSVC too
like image 63
Yakov Galka Avatar answered Sep 29 '22 20:09

Yakov Galka