c – 通过枚举值构造initializer_list包含随机值

前端之家收集整理的这篇文章主要介绍了c – 通过枚举值构造initializer_list包含随机值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在考虑问题 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.

原文链接:https://www.f2er.com/c/118823.html

猜你在找的C&C++相关文章