I was trying to write an compile-time valarray that could be used like this:
constexpr array a = { 1.0, 2.1, 3.2, 4.3, 5.4, 6.5 };
static_asse
Your current code should not compile according to current C++11 rules. When compiled with clang 3.2 I get the following error:
source.cpp:33:28: error: constexpr variable 'a' must be initialized by a constant
expression
constexpr array<double> a = { 1.0, 2.1, 3.2, 4.3, 5.4, 6.5 };
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is because std::initializer_list
s ctors and member functions begin
and end
are not labeled constexpr
. However, there already is a proposal to change this. BTW, libstdc++ already marks these as constexpr
.
Now the next problem is the lifetime of the underlying array of std::initializer_list
. This is explained in 8.5.4p6:
The array has the same lifetime as any other temporary object (12.2), except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary.
This means that the underlying array has the same lifetime as values
object, and expires at the end of your array
constructor when it exits. Therefore, _data
is pointing to expired memory and _data[n]
is undefined behavior.