samedi 15 décembre 2018

What is the lifetime of objects in a initializer list?

I have the impression that std::initializer_list might behave like literal strings in C++, and even further they might extend the lifetime of const references. Is that a correct assessment?

Can objest in an initializer_list be references later (without copying them), in local scope? in global scope?

For example this tests pass in GCC and clang. Is that just fortuitous?

#include<cassert>
#include<initializer_list> 
struct A{
    double const* p;
    A(std::initializer_list<double> il){ p = &*(il.begin() + 1); };
};
double f(){return 5.;}
int main(){
   A a1{1.,2.,3.};
   assert( *a1.p == 2. );
   A a2{1., f(), f()};
   assert( *a2.p == 5. );
}

Aucun commentaire:

Enregistrer un commentaire