C++ 方法返回损坏的值

C++ 方法返回损坏的值,c++,C++,当我回来的时候,我似乎得到了腐败的价值观。该图显示了循环的输出 // loop float *bo = getBoundaries(); // this calls the method displayed below cout << "\ngetDisplay: " << bo[0]; // loop float* getBoundaries() { cout << "\ngetB: " << x1; // this displays

当我回来的时候,我似乎得到了腐败的价值观。该图显示了循环的输出

// loop
float *bo = getBoundaries(); // this calls the method displayed below
cout << "\ngetDisplay: " << bo[0];
// loop

float* getBoundaries()
{
    cout << "\ngetB: " << x1; // this displays the correct value
    float boundaries[4] = {};
    boundaries[0] = x1;
    boundaries[1] = x2;
    boundaries[2] = y1;
    boundaries[3] = y2;
    cout << "\nfinal: " << boundaries[0]; // this also displays the correct value
    return boundaries;
}

//循环
float*bo=getbounders();//这将调用下面显示的方法
库特
使用指向超出范围的本地函数的指针是未定义的行为。当
getBoundries()
返回时,
Boundries
local超出范围,因此取消引用返回的指针可能会执行任何操作,包括使程序崩溃

由于数组不能按值返回,但结构可以,因此一个选项是返回包含数组的结构:

struct boundaries {
    float v[4];
};

boundaries getBoundaries() {
    boundaries b;

    b.v[0] = x1;
    b.v[1] = x2;
    b.v[2] = y1;
    b.v[3] = y2;

    return b;
}

// Then in your loop:
boundaries bo = getBoundaries();
cout << "\ngetDisplay: " << bo.v[0];
结构边界{
浮动v[4];
};
边界获取边界(){
边界b;
b、 v[0]=x1;
b、 v[1]=x2;
b、 v[2]=y1;
b、 v[3]=y2;
返回b;
}
//然后在循环中:
边界bo=getbounders();

如果无法编译您的程序,将启用所有警告,您应该会收到关于返回对临时数组的引用的警告。使用
std::vector
而不是
float*
,您的问题将消失。或者,对于小型固定大小数组,
std::array
.Hmm在我改变任何东西之前,这如何解释它的工作原理?@KarlMorrison这个答案中没有任何东西排除它按照您的预期工作的可能性。“未定义的行为”意味着任何事情都可能发生,包括程序按预期工作。可能发生的情况是,之前的代码生成器没有触及堆栈上为
边界分配的空间,但是当您更改某些内容时,该堆栈空间在包含循环的函数中被重新使用,因此在您有机会读取它之前,那里的数据已被删除。如果UB做了你想做的,那么一个看似无害的改变可能会突然使它崩溃。UB不好,阵列已经修复了一切!从现在起我将使用它。
struct boundaries {
    float v[4];
};

boundaries getBoundaries() {
    boundaries b;

    b.v[0] = x1;
    b.v[1] = x2;
    b.v[2] = y1;
    b.v[3] = y2;

    return b;
}

// Then in your loop:
boundaries bo = getBoundaries();
cout << "\ngetDisplay: " << bo.v[0];