在考虑问题
std::initializer list from already existing std::array without enumerating each element的解决方案时,我开发了与
bolov类似的机制,但没有构建对象,而只是初始化列表.我很惊讶我的解决方案不起作用,我无法弄清楚原因.
#include <initializer_list> #include <iostream> #include <array> template<typename T,std::size_t N,std::size_t... Is> std::initializer_list<T> array_to_init_list_helper(std::array<T,N> arr,std::index_sequence<Is...>) { return {arr[Is]...}; } template<typename T,std::size_t N> std::initializer_list<T> array_to_init_list(std::array<T,N> arr) { return array_to_init_list_helper(arr,std::make_index_sequence<N>{}); } int main() { std::array<int,5> arr{1,2,3,4,5}; auto init_list = array_to_init_list(arr); for (auto val : init_list) std::cout << val << " "; }
我是getting random values,而我希望获得arr的值.
解决方法
通过程序集
here(clang 4.0.0)和/或
here(GCC 7.1),很明显std :: initializer_list正在使用悬空指针,(我们都知道)它会产生看似随机的输出.
编辑
这个结果当然与Igor Tandetnik引用的评论一致,引用cppreference.com:
The underlying array is a temporary array of type const T[N],in which each element is copy-initialized (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the underlying array is the same as any other temporary object,except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions,such as for initializing a non-static class member). The underlying array may be allocated in read-only memory.