Related to this question: Return value or rvalue reference? - I found that the following example does appear to be unsafe, at least with g++ 6.1.0 and Boost 1.60.0.
#include <boost/optional.hpp>
struct A {
A();
A(const A&);
A(A&&);
~A();
int* begin();
int* end();
int* buf;
};
boost::optional<A> f();
int test() {
int res = 0;
for (int n : f().value())
res += n;
return res;
}
When I look in the generated assembly code, I definitely see A::~A()
being called before A::begin()
, A::end()
, etc.
The question is: What would be the least intrusive way to force a move construction before the temporary returned by f()
goes away?