【发布时间】:2015-02-05 01:53:52
【问题描述】:
这似乎类似于POD structs containing constant member,但有点相反。
#include <iostream>
struct A
{
int a;
};
union U
{
volatile A a;
long b;
};
int main()
{
U u1;
U u2;
u1.a.a = 12;
u2 = u1;
std::cout << u2.a.a << std::endl;
return 0;
}
g++ 4.8.3 编译这段代码没有错误并且运行正常:
$ g++ -std=c++03 a.cpp -o a_gcc
$ ./a_gcc
12
但是 clang++ 3.5.1 会产生错误(我已经手动包装了错误消息以防止代码框滚动):
$ clang++ -std=c++03 a.cpp -o a_clang
a.cpp:8:7: error: member function 'operator=' not viable: 'this'
argument has type 'volatile A', but function is not marked volatile
union U
^
a.cpp:3:8: note: 'operator=' declared here
struct A
^
a.cpp:20:5: note: implicit copy assignment operator for 'U' first
required here
u2 = u1;
^
1 error generated.
C++03 是否允许程序复制分配包含 volatile 结构的联合?我在 C++03 标准中找不到任何定义联合的默认复制构造函数的内容。
我想知道哪个编译器是正确的,或者标准在这一点上是否不明确。
编辑:我发现如果我使用复制构造而不是复制赋值,clang++ 和 g++ 都将编译程序而不会出错。具体来说,如果我将main 更改为:
int main()
{
U u1;
u1.a.a = 12;
U u2 = u1;
std::cout << u2.a.a << std::endl;
return 0;
}
.. 然后它会工作。我想知道为什么 clang++ 对它们的处理方式不同。
【问题讨论】:
-
如果在
union U:volatile U& operator =(const volatile U&) volatile中添加一个用户定义的赋值运算符呢?或者也许只有其中一些volatiles? -
为什么不让工会的实例变得易变,而不是让工会的成员成为易变的?用这种方式推断它的行为似乎更容易。
-
@JohnZwinck 因为那样就不会导致这个问题了。
标签: c++ language-lawyer volatile unions c++03