constexpr array and std::initializer_list

北城余情 提交于 2019-11-29 11:27:36

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_lists 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!