在过去的几天里,我在C++中调试了一个涉及lambda的奇怪问题。我已经将问题简化为以下症状:
this
object)this
总是被copy捕获,因此lambda应该有自己的this
指针,该指针指向App
object)x86
架构下运行良好时(请参阅:I create the lambda on the heap (并在App
对象中保存指向它的指针)),bug does not printf()
not bug不会发生bug如果优化被关闭(即如果我设置了x86
标志),则不会发生bug。当optimization设置为-O2
.时会出现此错误
下面是我能想到的导致问题的最简单的、可编译的代码示例。
#include <iostream>
#include <functional>
class App {
public:
std::function<void*()> test_;
void Run() {
// Enable this line, ERROR is printed
// Disable this line, app runs o.k.
std::cout << "This print statement causes the bug below!" << std::endl;
test_ = [this] () {
return this;
};
void* returnedThis = test_();
if(returnedThis != this) {
std::cout << "ERROR: 'this' returned from lambda (" << returnedThis
<< ") is NOT the same as 'this' (" << this << ") !?!?!?!?!"
<< std::endl;
} else {
std::cout << "Program run successfully." << std::endl;
}
}
};
int main(void) {
App app;
app.Run();
}
在目标设备上运行时,我得到以下输出:
This print statement causes the bug below!
ERROR: 'this' returned from lambda (0xbec92dd4) is NOT the same as 'this'
(0xbec92c68) !?!?!?!?!
如果我尝试取消引用损坏的this
,我通常会得到一个分段错误,这就是我第一次发现错误的原因。
编译器设置
arm-poky-linux-gnueabi-g++ -march=armv7-a -marm -mfpu=neon -std=c++14 \
-mfloat-abi=hard -mcpu=cortex-a9 \
--sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-O2 -pipe -g -feliminate-unused-debug-types
链接器设置
arm-poky-linux-gnueabi-ld \
--sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed
编译器版本
~$ arm-poky-linux-gnueabi-g++ --version
arm-poky-linux-gnueabi-g++ (GCC) 6.2.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
这可能是一个编译器错误吗?
https://stackoverflow.com/questions/44830566
复制相似问题