抛开所有可维护性和读取问题,这些代码行是否会产生不确定的行为?
float a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
Run Code Online (Sandbox Code Playgroud) 我对这里发生的事情有一个模糊的想法......它与此有关,但我想知道为什么clang ++和g ++处理这个问题的方式不同.这里的未定义行为在哪里?注意:这与模板无关 - 我只是使用它们来使示例更紧凑.这都是关于它的类型whatever
.
#include <iostream>
#include <vector>
template <typename T>
void test()
{
T whatever = 'c';
const char a = 'a';
std::cout << "begin: " << (void*)&a << std::endl;
const char & me = (true ? a : whatever);
std::cout << "ref: " << (void*)&me << std::endl;
}
int main(int argc, char**argv)
{
test<const char>();
test<char>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
gcc输出(测试高达4.9.3):
begin: 0x7fffe504201f
ref: 0x7fffe504201f
begin: 0x7fffe504201e
ref: 0x7fffe504201f
Run Code Online (Sandbox Code Playgroud)
clang 3.7.0输出:
begin: 0x7ffed7b6bb97
ref: …
Run Code Online (Sandbox Code Playgroud)