This question already has an answer here:
- Initializer list of variables 1 answer
Following this answer https://stackoverflow.com/a/29074955/1098041
I have a curious behavior.
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);
}
Output in debug :
3
3
Output in release:
3
2686868 // some garbage.
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.