我们在 SunCC 5.12 到 5.14 下捕获编译警告。其他编译器,如 Clang、GCC、ICC 和 MSVC 不会提示。我不确定诊断结果,因为我以前没有遇到过。
有问题的代码是针对 BigInteger
class 的有问题的 union 随之而来。该类(class)试图找到最大的机器字,以适应可以使用 umulx
等硬件执行的进位加法和乘法运算。
class Dword
{
...
private:
320 union
321 {
322 #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
323 dword m_whole;
324 #endif
325 struct
326 {
327 #ifdef IS_LITTLE_ENDIAN
328 word low;
329 word high;
330 #else
331 word high;
332 word low;
333 #endif
334 } m_halfs;
335 };
336 };
这是警告:
[ 3%] Building CXX object CMakeFiles/cryptopp-object.dir/integer.cpp.o
/opt/solarisstudio12.3/bin/CC -fPIC -native -m64 -template=no%extdef -o CMakeFiles/cryptopp-object.dir/integer.cpp.o
-c /export/home/jwalton/cryptopp/integer.cpp
CC: Warning: -xchip=native detection failed, falling back to -xchip=generic
"/export/home/jwalton/cryptopp/integer.cpp", line 335: Warning: Types cannot be declared in anonymous union.
1 Warning(s) detected.
根据 Microsoft 在 Anonymous Unions :
Simply omitting the class-name portion of the syntax does not make a union an anonymous union. For a union to qualify as an anonymous union, the declaration must not declare an object.
如果我理解正确,我们确实有一个匿名结构,因为没有人可以实例化从第 325 行开始的私有(private)成员 struct {...} m_halfs
。然后, SunCC 提示匿名 union 有成员 struct {...} m_halfs
。对吗?
如果 struct {...} m_halfs
是问题所在,那么我们如何才能以可移植的方式清除它?
如果这不是问题,那么 SunCC 在提示什么?
我必须小心这个问题是如何解决的。性能是重中之重,代码在关键路径上。此外,我们还支持现代编译器的 GCC 3 和 VC++ 6.0;和 C++03、C++11、C++14 和 C++17。
最后一个问题是,我们是否应该“什么都不做”并在 Solaris 上接受它?
最佳答案
N4296 (这是 C++ 17 标准的初稿)说:
A union of the form
union { member-specification } ;
is called an anonymous union; it defines an unnamed object of unnamed type. Each member-declaration in the member-specification of an anonymous union shall either define a non-static data member or be a static_assert-declaration. [ Note: Nested types, anonymous unions, and functions cannot be declared within an anonymous union. — end note]
这正是您所拥有的 - 您没有类名或成员名,因此不允许您为 m_halfs
发明新的结构类型。我建议将结构定义移出 union 。
class Dword
{
...
private:
struct word_struct
{
#ifdef IS_LITTLE_ENDIAN
word low;
word high;
#else
word high;
word low;
#endif
};
union
{
#ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
dword m_whole;
#endif
word_struct m_halfs;
};
};
这不会对性能产生影响(但请注意,这种使用 union 来访问变量的不同部分的技巧可能会违反严格的别名规则 - 这意味着您的程序可能具有未定义的行为。)
关于c++ - SunCC 5.12 到 5.14 和 "Types cannot be declared in anonymous union",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39505525/