2

I maintain an open source program and one of my users reported that it won't compile under clang, which I've never used before. One of the errors that I'm getting is *Warning: qualifier on function type 'junky_t' (aka 'void (const int &, const int &)') has unspecified behavior.*. I've created a small program that demonstrates the issue:

typedef void junky_t(const int &foo,const int &bar);

class demo {
public:;
    const junky_t *junk;
};

And here's what happens when I try to compile:

$clang -DHAVE_CONFIG_H  -g -g -O3 -Wall -MD -Wpointer-arith -Wshadow -Wwrite-strings -Wcast-align -Wredundant-decls -Wdisabled-optimization -Wfloat-equal -Wmultichar -Wmissing-noreturn -Woverloaded-virtual -Wsign-promo -funit-at-a-time -Weffc++  -D_FORTIFY_SOURCE=2  -MT demo.o -MD -MP -c -o demo.o demo.cpp

demo.cpp:5:5: warning: qualifier on function type 'junky_t' (aka 'void (const int &, const int &)') has unspecified behavior
    const junky_t *junk;
    ^~~~~~~~~~~~~
1 warning generated.

That is, class demo has a function pointer to a function that has a signature that takes a number of const references. The const in the class demo is supposed to prevent junk from being changed. However apparently it's ambiguous because the function itself might be considered const, which it is not. I do not have a problem compiling this with gcc or llvm but it will not compile with clang on a Mac. What should I do?

vy32
  • 28,461
  • 37
  • 122
  • 246

1 Answers1

3

This is not unspecified behavior. The warning of clang is wrong. Your code is legal c++. The Standard (C++11) states, that cv-qualifiers on top of a function type are ignored.

Hence, it doesn't make any sense to put a const qualifier on top of a function type. If you want your pointer to be const then write

junky_t * const junk;

otherwise just write

junky_t * junk;

MWid
  • 4,429
  • 3
  • 20
  • 20
  • The warning is reasonable. The "const" has no effect. But clearly one would expect that if you write "const" then something becomes const and that isn't going to happen. Compilers give warnings for code that is perfectly legal, but likely to be not what the author intended. Both alternatives that you wrote are much more likely to do what you wanted them to do. Actually the thread starter wrote: "The const in the class demo is supposed to prevent junk from being changed." It doesn't do that, so it's a good warning. – gnasher729 Mar 18 '14 at 22:08
  • @gnasher729 No, the warning (message) is not reasonable, because it states that `const` has _unspecified behavior_. This is wrong as I pointed out. But I agree, that it is a good thing to warn on such a use of a qualifier (but with a different message). – MWid Mar 19 '14 at 10:48