Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

a temporary object in range_based for loop related question in c++

in this page Range-based for loop on a temporary range, user Barry mentioned that the following is not affected by the destroyed temporary object, and I tested member v indeed exists throughout the for loop(as the destructor ~X didn’t get called throughout the for loop). Can anyone explain why for me please? Many thanks!

struct X {
    std::vector<int> v;
    ~X()
    {
    }
};
X foo()
{
return X();
}

for (auto e : foo().v) {
    // ok!
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

According to cppreference, a range-based for loop is equivalent to:

{
    auto && __range = range-expression ;
    for (auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin)
    {
        // ...
    }
}

and in your example, the temporary returned by foo is part of range-expression (in fact it is range-expression, pretty much) so its lifetime is that of the entire loop. After all, a range-based for loop would be of little value if it worked any other way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading