简体   繁体   English

负数数组没有错误

[英]No error for negative-size array

Why don't I get an error trying to create a negative-size array? 为什么在创建负大小的数组时没有出现错误?

#include <array>

int main()
{
    std::array<int, -1> arr;
}

With -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC I get no error. 使用-D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC我没有任何错误。 Is this intended behavior? 这是预期的行为吗?

No it's not legal. 不,这是不合法的。 There's nothing about the specification of std::array that explicitly prevents this, but it's illegal because of narrowing conversions. 关于std::array的规范并没有明确地阻止这种情况的发生,但是由于转换范围狭窄,它是非法的。

§14.3.2/5: §14.3.2/ 5:

For a non-type template-parameter of integral or enumeration type, conversions permitted in a converted constant expression (5.19) are applied. 对于整数或枚举类型的非类型模板参数,将应用转换后的常量表达式(5.19)中允许的转换。

§5.19/3: §5.19/ 3:

A converted constant expression of type T is a literal constant expression, implicitly converted to type T, where the implicit conversion (if any) is permitted in a literal constant expression and the implicit conversion sequence contains only user-defined conversions, lvalue-to-rvalue conversions (4.1), integral promotions (4.5), and integral conversions (4.7) other than narrowing conversions (8.5.4) 类型T的转换常量表达式是文字常量表达式,它隐式转换为类型T,其中文字常量表达式中允许隐式转换(如果有),并且隐式转换序列仅包含用户定义的转换,即左值到右值转化(4.1),积分促销(4.5)和积分转化(4.7),而不是缩小转化(8.5.4)

The only way to get GCC to complain is to enable -Wsign-conversion . 使GCC抱怨的唯一方法是启用-Wsign-conversion This is a known bug and they haven't made any movement to fix it. 这是一个已知的错误 ,他们尚未采取任何行动来修复它。

In Clang you get the expected error message: 在Clang中,您会收到预期的错误消息:

error: non-type template argument evaluates to -1, which cannot be 
narrowed to type 'std::size_t' (aka 'unsigned long') [-Wc++11-narrowing]
    std::array<int, -1> arr;

Type of std::array is: std::array类型是:

template< 
    class T, 
    std::size_t N 
> struct array;

When you initialize second template parameter with -1 , it is implicitly converted to a very large value as std::size_t is unsigned (which is illegal in C++ as pointed by other answer and it should be diagnosed). 当您使用-1初始化第二个模板参数时,它会隐式转换为一个非常大的值,因为std::size_tunsigned (在C ++中,由其他答案指出这是非法的,应该对其进行诊断)。

Another possibility is that your arr is optimized out. 另一种可能性是您的arr已优化。 You can confirm this by adding -fdump-tree-optimized flag to gcc command line. 您可以通过在gcc命令行中添加-fdump-tree-optimized标志来确认这一点。

If you ensure arr is not optimized out, I hope you should get the following warning : 如果您确保arr没有被优化,希望您收到以下警告

prog.cpp:5:25: error: size of variable 'arr' is too large
     std::array<int, -1> arr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM