gpt4 book ai didi

c++ - 警告从 lambda 返回捕获的引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:00 25 4
gpt4 key购买 nike

我尝试使用 lambda 有条件地将引用绑定(bind)到两个变量之一:

int foo, bar;
int &choice = [&]() -> int & {
if (true /* some condition */) {
return foo;
} else {
return bar;
}
}();

这会在 clang 3.4 中产生警告:

stack_stuffing.cpp:5:20: warning: reference to stack memory associated with
local variable 'foo' returned [-Wreturn-stack-address]
return foo;
^~~
stack_stuffing.cpp:7:20: warning: reference to stack memory associated with
local variable 'bar' returned [-Wreturn-stack-address]
return bar;
^~~

但我只返回对调用 lambda 的范围内的堆栈内存的引用。此行为是指定的、未指定的还是 clang 错误?

最佳答案

这确实是 Clang 中的一个错误 - 您通过引用正确地捕获了两个变量并且没有创建悬挂引用。我假设每当有人返回对任何东西(无论是 lambda 还是函数)中的堆栈变量的引用时,Clang 都会自动发出警告。

clang 3.5 does not show this warning anymore , neither does GCC 4.9.0 .

关于c++ - 警告从 lambda 返回捕获的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com