小编Rem*_*mco的帖子

如何在范围表达式中延长临时的生命周期?

在使用ranged-for循环时,我正在获取悬空引用.考虑以下C++ 14表达式(下面的完整示例程序):

    for(auto& wheel: Bike().wheels_reference())
        wheel.inflate();
Run Code Online (Sandbox Code Playgroud)

它的输出是:

 Wheel()
 Wheel()
 Bike()
~Bike() with 0 inflated wheels.
~Wheel()
~Wheel()
 Wheel::inflate()
 Wheel::inflate()
Run Code Online (Sandbox Code Playgroud)

显然有些事情是非常错误的.车轮超出其使用寿命,结果为0,而不是预期的2.

一个简单的解决方法是为Bikein 引入一个变量main.但是,我不控制代码mainWheel.我只能改变结构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()" << …
Run Code Online (Sandbox Code Playgroud)

c++ reference ranged-loops c++14

6
推荐指数
1
解决办法
240
查看次数

标签 统计

c++ ×1

c++14 ×1

ranged-loops ×1

reference ×1