vendredi 17 août 2018

Const reference as a member of a class insconsistency

In one create a const reference to a temporary its life is extended. Is it a good feature of the language although it is presented sometimes like an exception to other rules. https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

However this doesn't work when the const reference is part the member of a class. Is this an inconsistency of the language?

Example code:

int f(int a){return a + 5;}
int main(){
    int const& b = f(2);
    assert(b == 7); // ok, not a dangling reference

    struct single{
        int const& m_;
        single(int const& m) : m_(m){}
    };
    single s{f(3)};
    assert(s.m_ == 8); // fails, dangling reference

    struct pair{
        int const& m1_;
        int const& m2_;
        pair(int const& m1, int const& m2) : m1_(m1), m2_(m2){}
    };

    pair p{f(3), f(4)};
    assert( p.m1_ == 8 ); // fails, dangling reference
}

Is there a workaround for this to work or at least behave more consistently?

I found this to be a limiting factor in a few contexts now. For example, List using with references, changes behavior when used as a member and https://stackoverflow.com/a/51878764/225186

Aucun commentaire:

Enregistrer un commentaire