std :: initializer_list的底层数组的生命周期是多少? [英] What is the lifetime of the array underlying a std::initializer_list?

查看:160
本文介绍了std :: initializer_list的底层数组的生命周期是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此答案 http://stackoverflow.com/a/29074955/1098041

我有一个奇怪的行为。

在Debug中我得到期望的输出,但是在发布在 test fonction中获取垃圾。

In Debug I get the expected output, however in release (I'm using mingw on windows) I get garbage in the test fonction.

#include <iostream>
#include <initializer_list>

template <class T>
struct array
{
    T     *ptr;
    size_t len;

    array() { clear(); }
    array( T *p, size_t l ) { assign(p,l); }

    inline void clear() { ptr=nullptr; len=0; }
    inline void assign( T *p, size_t l ) { ptr=p; len=l; }

    inline T& operator[] ( size_t i ) const { return ptr[i]; }
};

template <class T>
inline array<const T> wrap( std::initializer_list<T> lst )
    { return array<const T>( lst.begin(), lst.size() ); }


void test( int a, int b, int c )
{
    auto ar = wrap({a,b,c});
    std::cout<< ar[1] << std::endl;
}

int main()
{
    auto a = wrap({1,2,3});
    std::cout<< a[2] << std::endl;

    test(1,2,3);
}

在调试中输出:

3
3

3
2686868 // some garbage.


$ b <

Can anyone explain to me how debug/release mode influences the lifetime of the initializer_list underlying array ? Or provide some other explanation for this behavior.

推荐答案

  auto a = wrap({1,2,3});

initializer_list 底层数组)在该表达式的末尾结束,因此 a 包含悬空指针。

The lifetime of the initializer_list (and its underlying array) ends at the end of that expression, so a contains a dangling pointer.

c $ c> std :: cout<< a [2] 有未定义的行为。类似地,对于 test 中的代码, std :: cout a [1]`也是未定义的行为。

That means std::cout<< a[2] has undefined behaviour. Similarly for the code in test, std::cout <<a[1]` is also undefined behaviour.


任何人都可以向我解释调试/释放模式如何影响initializer_list底层数组的生命周期?或者为此行为提供其他解释。

Can anyone explain to me how debug/release mode influences the lifetime of the initializer_list underlying array ? Or provide some other explanation for this behavior.

这是未定义的行为。

任何事情都可能发生。

在发布模式下,编译器对事物进行不同的优化,因此栈上的变量布局是不同的,因此具有未定义行为的代码可能会有所不同。

In release mode the compiler optimizes things differently, so the layout of variables on the stack is different, so code with undefined behaviour might do something different. Or it might not.

这不是特定于 initializer_list ,你会得到类似的未定义的行为

This isn't even specific to initializer_list, you'd get similar undefined behaviour for any temporary object that you keep pointers into:

wrap( std::vector<int>(1, 1) );

这篇关于std :: initializer_list的底层数组的生命周期是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆