首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >lambda捕获的"this“不正确。GCC编译器bug?

lambda捕获的"this“不正确。GCC编译器bug?
EN

Stack Overflow用户
提问于 2017-06-30 00:28:36
回答 2查看 1.2K关注 0票数 18

在过去的几天里,我在C++中调试了一个涉及lambda的奇怪问题。我已经将问题简化为以下症状:

  • The this object)
  • It指针在lambda print中被损坏(注意:this总是被copy捕获,因此lambda应该有自己的this指针,该指针指向App object)
  • It,只有当存在语句时才会发生,并在创建lambda之前调用。print语句可能看起来完全无关(例如,print "Hello!")。当cross-compiling.
  • It编译并在标准编译器 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.

这可能是一个编译器错误吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-19 21:14:39

这似乎是gcc 6.2中的一个编译器错误,请看:

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77686

解决方法:

  • 使用-fno-schedule-insns2标志(正如gbmhunter指出的,请参阅下面的注释)。
  • 不使用-O2优化或更高版本。
票数 4
EN

Stack Overflow用户

发布于 2017-07-04 08:32:30

听起来像是下面的编译器错误:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77933 (它只影响使用O1优化或更高版本生成的代码)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44830566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档