相关疑难解决方法(0)

使用三元运算符初始化引用变量?

抛开所有可维护性和读取问题,这些代码行是否会产生不确定的行为?

float  a = 0, b = 0;
float& x = some_condition()? a : b;
x = 5;
cout << a << ", " << b;
Run Code Online (Sandbox Code Playgroud)

c++ reference ternary-operator

15
推荐指数
2
解决办法
3265
查看次数

clang和gcc之间const参考三元运算符的地址差异

我对这里发生的事情有一个模糊的想法......它与此有关,但我想知道为什么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)

c++ gcc ternary-operator clang++

5
推荐指数
1
解决办法
142
查看次数

标签 统计

c++ ×2

ternary-operator ×2

clang++ ×1

gcc ×1

reference ×1