在 C++ 三元运算符中使用字符串常量是对非左值数组的无效使用吗?
Is using a string constant in C++ ternary operator an invalid use of non-lvalue array?
我有代码使用三元运算符检查条件,然后 returns 指向 C 字符串常量的指针或抛出异常。
奇怪的是,只有当我从三元运算符的一个路径throw
时,编译才会失败。如果我在两边都放一个字符串常量,一切都会编译。
// this line gives no compilation error
auto str = condition ? "foo" : "bar";
// this line gives "error: invalid use of non-lvalue array"
auto str = condition ? "foo" : throw std::runtime_error{"bad"};
这个问题已经开始出现在 gcc 9.1 中。多年来,我一直使用上述两种模式的行,它们在 clang 和早期版本的 gcc 中编译时没有警告。
上面的模式实际上是无效的,还是 gcc 9.1 中的编译器错误?
你是对的。如果另一个操作数是 throw-expression,则三元运算符传播一个操作数的类型和值类别。 conditional-expression 是类型 const char[4]
的左值。 auto
然后推导 const char*
。这里没有"invalid use of non-lvalue array"
此外,代码编译 fine 时会发出 clang 声。我会说这是 GCC 的一个错误。
我有代码使用三元运算符检查条件,然后 returns 指向 C 字符串常量的指针或抛出异常。
奇怪的是,只有当我从三元运算符的一个路径throw
时,编译才会失败。如果我在两边都放一个字符串常量,一切都会编译。
// this line gives no compilation error
auto str = condition ? "foo" : "bar";
// this line gives "error: invalid use of non-lvalue array"
auto str = condition ? "foo" : throw std::runtime_error{"bad"};
这个问题已经开始出现在 gcc 9.1 中。多年来,我一直使用上述两种模式的行,它们在 clang 和早期版本的 gcc 中编译时没有警告。
上面的模式实际上是无效的,还是 gcc 9.1 中的编译器错误?
你是对的。如果另一个操作数是 throw-expression,则三元运算符传播一个操作数的类型和值类别。 conditional-expression 是类型 const char[4]
的左值。 auto
然后推导 const char*
。这里没有"invalid use of non-lvalue array"
此外,代码编译 fine 时会发出 clang 声。我会说这是 GCC 的一个错误。