This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Questions about placement of qualifiers in member functions


Ian Lance Taylor wrote:

> I thought this was a logical thing to write:
>
> class C { public: int (*f())() const; };
> int foo(const C c) { return (*c.f())(); }

No, it's ill-formed, the 'const' on the first line is misplaced.

> However, when I compile it, I get this:
> /home/ian/foo4.cc: In function `int foo(C)':
> /home/ian/foo4.cc:2: error: passing `const C' as `this' argument of
> `int (* C::f())()' discards qualifiers

GCC is incorrectly accepting the first line. It should whine about the
spourious const but it does not, and silently ignores it. Then, it correctly
emits another error because of the cv-qualifier mismatch.

> This seems strange to me, because it seems like the `const' on the
> first line is just being ignored.

It is. I believe it should be a hard error.

> I found out that I could write the declaration like this:
>
> class C { public: int (*f() const)(); };
> int foo(const C c) { return (*c.f())(); }
>
> and it would compile without error.

Yes, this is the correct way to define a pointer to a const function. See my
examples below.

> 1) Is it correct that a member function qualifier should be written
>    within the declaration when the member function returns a pointer
>    to a function?  Why not write the qualifer after the list of
>    parameters, as is normally done?

Because you're misreading. For instance:

int (*f(float))(double);

This is equivalent to:

typedef int (*t)(double);
t (*f)(float);

not to:

typedef int (*t)(float);
t (*f)(double);

In other words, when you write:

A (*f(B))(C)

B is the parameter list for function F, while C is the parameter list for the
pointer-to-function which is returned. This is why the const qualifier has to
be placed like this:

A (*f(B) const)(C)

if you want to say that f() can be called only on const objects.

 > 2) If the answer to question 1 is that this is correct, then why
>    doesn't g++ warn about the `const' when compiling C::f in the first
>    function above?  That `const' appears to mean nothing, which to me
>    means that its appearance ought to be a syntax error.  If not, then
>    what does it mean?

I think it's a bug in GCC. It seems that the const placed at the end, as in:

int (*f())() const;

would qualify the type of the function pointer returned by the function, but
cv-qualifiers on function-types are ill-formed. GCC *used* to accept them as an
extension, so maybe this is a leftover. Nathan, do you agree with me?

Giovanni Bajo



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]