[英]Why does this const specifier have unspecified behavior?
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.我维护一个开源程序,我的一个用户报告说它不会在我以前从未使用过的
clang
下编译。 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.* .我遇到的错误之一是*Warning: qualifier on function type 'junky_t'(又名 'void (const int &, const int &)')具有未指定的行为。* 。 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.也就是说,类
demo
有一个函数指针,指向一个函数,该函数的签名带有多个const 引用。 The const
in the class demo
is supposed to prevent junk
from being changed.类
demo
的const
应该防止junk
被更改。 However apparently it's ambiguous because the function itself might be considered const
, which it is not.然而显然它是模棱两可的,因为函数本身可能被认为是
const
,而事实并非如此。 I do not have a problem compiling this with gcc
or llvm
but it will not compile with clang
on a Mac.我用
gcc
或llvm
编译它没有问题,但它不会在 Mac 上用clang
编译。 What should I do?我该怎么办?
This is not unspecified behavior .这不是未指明的行为。 The warning of clang is wrong.
叮当的警告是错误的。 Your code is legal c++.
您的代码是合法的 C++。 The Standard (C++11) states, that cv-qualifiers on top of a function type are ignored.
标准 (C++11) 规定,忽略函数类型顶部的 cv 限定符。
Hence, it doesn't make any sense to put a const qualifier on top of a function type.因此,将 const 限定符放在函数类型之上没有任何意义。 If you want your pointer to be const then write
如果你希望你的指针是 const 然后写
junky_t * const junk;
otherwise just write否则就写
junky_t * junk;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.