G++编译旧C++回调代码时的数组越界警告是否合理?
G++高优化级别下的数组越界警告分析
我在测试Rich Hickey提出的一款旧C回调实现,使用G 14.2以g++ -c -Wall -O2编译以下简化代码时,触发了数组越界警告。该警告从G++ 11版本开始出现,旧版本无此提示,且在-O0或-O1编译选项下会消失。
测试代码
#include <cstddef> #include <cstring> struct FunctorBase { typedef void (FunctorBase::*MethodPtr)(); template<typename Method> Method get_method() const { return *static_cast<Method const*>(static_cast<void const*>(_method)); } FunctorBase(const void* method, std::size_t sz) : _method{} { std::memcpy(_method, method, sz); } alignas (MethodPtr) unsigned char _method[sizeof(MethodPtr)]; }; template<class P1> struct Functor1 : FunctorBase { typedef void (*Thunk)(const FunctorBase&, P1); Functor1(Thunk t, const void* mf, size_t sz) : FunctorBase(mf, sz), thunk(t) {} void operator()(P1 p1) const { thunk(*this, p1); } Thunk thunk; }; template<class Callee, class Method> struct MemberOf1stArgTranslator1 : Functor1<Callee> { MemberOf1stArgTranslator1(const Method& m) : Functor1<Callee>(thunk, &m, sizeof(Method)) {} static void thunk(const FunctorBase& ftor, Callee callee) { (callee.*ftor.get_method<Method>())(); } }; template<class P1, class TRT, class CallType> inline MemberOf1stArgTranslator1<P1, TRT (CallType::*)()> create_functor(Functor1<P1>*, TRT (CallType::*const& f)()) { typedef TRT (CallType::*Method)(); return MemberOf1stArgTranslator1<P1, Method>(f); } struct MyCallee { void my_f() {} }; void f() { typedef Functor1<MyCallee&> F; F f = create_functor((F*)0, &MyCallee::my_f); MyCallee c; f(c); }
编译器警告信息
In static member function 'static void MemberOf1stArgTranslator1<Callee, Method>::thunk(const FunctorBase&, Callee) [with Callee = MyCallee&; Method = void (MyCallee::*)()]', inlined from 'void Functor1<P1>::operator()(P1) const [with P1 = MyCallee&]' at <source>:31:7, inlined from 'void f()' at <source>:65:5: <source>:44:42: warning: array subscript 'int (**)(...)[0]' is partly outside array bounds of 'MyCallee [1]' [-Warray-bounds=] 44 | (callee.*ftor.get_method<Method>())(); | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~ <source>: In function 'void f()': <source>:64:13: note: object 'c' of size 1 64 | MyCallee c; | ^
疑问
我完全无法理解这个警告——代码中并没有MyCallee类型的数组。想请教:这个编译器提示的具体含义是什么?这是代码存在真实问题,还是编译器的误报?
内容的提问来源于stack exchange,提问作者Markus
相关产品推荐
相关产品推荐

