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. Is this intended behavior?
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. 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.
§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/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)
The only way to get GCC to complain is to enable -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:
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:
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).
Another possibility is that your arr
is optimized out. You can confirm this by adding -fdump-tree-optimized
flag to gcc command line.
If you ensure arr
is not optimized out, I hope you should get the following warning:
prog.cpp:5:25: error: size of variable 'arr' is too large
std::array<int, -1> arr;