0

There is the following piece of code

#include <iostream>
#include <vector>

class A
{
public:
    auto foo()
    {
        //std::vector<int> vec;
        return std::vector<int>{} ;
    }
};

auto bar()
{
    return A();
}
int main() {
    for(auto && el : bar().foo())
    {

    }
}

In my point of view the code above has UB due to dangling reference? Is this correct? I have the impression that in the code above the follwing statement applies

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data member to which the temporary was bound, does not affect its lifetime.

However the sanitiser does not detect this issue

Moreover cppreference refers the following

If range-expression returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the forwarding reference __range. Lifetimes of all temporaries within range-expression are not (until C++23) extended if they would otherwise be destroyed at the end of range-expression (since C++23).

Have a look in the following demo

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
getsoubl
  • 808
  • 10
  • 25
  • Because both functions return their objects *by value* there are no dangling references. – Some programmer dude Mar 06 '23 at 08:18
  • This should be fine. `el` is bound to the temporary object returned by `foo()`. – songyuanyao Mar 06 '23 at 08:20
  • 2
    This is in effect a duplicate as marked, but I don't think the question that was *intended* to be asked is a duplicate. – Sebastian Redl Mar 06 '23 at 08:21
  • // if foo() returns by value for (auto& x : foo().items()) { /* .. */ } // until C++23 undefined behavior , What in cpp reference is used as example . If I changed the example above to const & then still continues to be ok? – getsoubl Mar 06 '23 at 08:26
  • 1
    @getsoubl It's still UB until C++23. – songyuanyao Mar 06 '23 at 08:33
  • @songyuanyao , you mean my demo is UB? But then sanitizer why does not detect it – getsoubl Mar 06 '23 at 08:35
  • 1
    @getsoubl No, your code is different. I suppose the code intended by cppreference.com should be sth like https://godbolt.org/z/T8bre5e6W. The point is that the lifetime of temporary returned by `bar()` won't be extened until C++23 which might cause issues (like binding reference to data member of the temporary). – songyuanyao Mar 06 '23 at 08:42

0 Answers0