与此问题相关:Return value or rvalue reference? - 我发现以下示例确实不安全,至少对于 g++ 6.1.0 和 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;
}
当我查看生成的汇编代码时,我肯定看到 A::~A()
在 A::begin()
之前被调用,A::end()
等
问题是:在 f()
返回的临时值消失之前,强制移动构造的侵入性最小的方法是什么?
最佳答案
创建显式临时文件:
for (int n : A(f().value())) { /* ... */ }
关于c++ - 如何延长访问器返回的右值引用的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199525/