在使用 ranged-for 循环时,我得到了悬空引用。考虑以下 C++14 表达式(下面的完整示例程序):
for(auto& wheel: Bike().wheels_reference())
wheel.inflate();
它的输出是:
Wheel()
Wheel()
Bike()
~Bike() with 0 inflated wheels.
~Wheel()
~Wheel()
Wheel::inflate()
Wheel::inflate()
显然有些事情出了问题。轮子在其生命周期之外被访问,结果为 0,而不是预期的 2。
一个简单的解决方法是为Bike
in引入一个变量main
。但是,我不控制main
or中的代码Wheel
。我只能更改 struct Bike
。
有没有办法只通过改变来修复这个例子Bike
?
一个成功的解决方案要么在编译时失败,要么计算 2 个充气轮胎并且在其生命周期之外不接触任何对象。
附录:编译准备好的源码
#include <cstdlib>
#include <iostream>
#include <array>
#include <algorithm>
using std::cout;
using std::endl;
struct Wheel
{
Wheel() { cout << " Wheel()" << endl; }
~Wheel() { cout << "~Wheel()" << endl; }
void inflate() { inflated = true; cout << " Wheel::inflate()" << endl; }
bool inflated = false;
};
struct Bike
{
Bike() { cout << " Bike()" << endl; }
~Bike() {
cout << "~Bike() with " << std::count_if(wheels.begin(), wheels.end(),
[](auto& w) { return w.inflated; }) << " inflated wheels." << endl;
}
std::array<Wheel, 2>& wheels_reference() { return wheels; }
std::array<Wheel, 2> wheels{Wheel(), Wheel()};
};
int main()
{
for(auto& wheel: Bike().wheels_reference())
wheel.inflate();
return EXIT_SUCCESS;
}