On Thu, Nov 03, 2022 at 02:54:12PM -0400, Jason Merrill wrote: > On 11/1/22 18:06, Marek Polacek wrote: > > -Wdangling-reference complains here: > > > > std::vector<int> v = ...; > > std::vector<int>::const_iterator it = v.begin(); > > while (it != v.end()) { > > const int &r = *it++; // warning > > } > > > > because it sees a call to > > __gnu_cxx::__normal_iterator<const int*, std::vector<int> >::operator* > > which returns a reference and its argument is a TARGET_EXPR representing > > the result of > > __gnu_cxx::__normal_iterator<const int*, std::vector<int> >::operator++ > > But 'r' above refers to one of the int elements of the vector 'v', not > > to a temporary object. Therefore the warning is a false positive. > > > > I suppose code like the above is relatively common (the warning broke > > cppunit-1.15.1 and a few other projects), so presumably it makes sense > > to suppress the warning when it comes to member operator*. In this case > > it's defined as > > > > reference > > operator*() const _GLIBCXX_NOEXCEPT > > { return *_M_current; } > > > > and I'm guessing a lot of member operator* are like that, at least when > > it comes to iterators. I've looked at _Fwd_list_iterator, > > _Fwd_list_const_iterator, __shared_ptr_access, _Deque_iterator, > > istream_iterator, etc, and they're all like that, so adding #pragmas > > would be quite tedious. :/ > > > Bootstrapped/regtested on x86_64-pc-linux-gnu, ok for trunk? > > OK.
Thanks. > It also occurred to me that we should avoid warning if the reference we're > initializing is a non-const lvalue reference, which can't bind to a > temporary. Yup; amusingly I noticed that too while working with the reduced version of the testcase, which I deliberately didn't end up using, and which reduced to 'int&' rather than 'const int&'. > Maybe also if the function returns a non-const lvalue reference. Ok. Expect a patch soon. Marek