为什么lambda在clang而不是gcc崩溃?

Arn*_*old 1 c++ lambda gcc clang illegal-instruction

这个程序与clang崩溃了

#include <iostream>
#include <string>
#include <mutex>
#include <functional>

int main(int argc, char **argv)
{
    auto m = std::function<void()>( [](){
        int r = std::rand() % 100;
        if (r < 50)
        {
            return r; //should not return
        }
    });
    for(int i=0;i<100;i++)
        m();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

报告:

pt@test$ clang++ -o test test1.cpp  -std=c++11
    test1.cpp:14:5: warning: control may reach end of non-void lambda [-Wreturn-type]
    });
    ^
1 warning generated.
pt@test$ ./test
Illegal instruction (core dumped)
Run Code Online (Sandbox Code Playgroud)

但是,它并没有崩溃g++.

我的困惑是,因为它会导致崩溃,为什么不在clang编译时将其视为错误?


更新

考虑以下代码

auto lMayNotReturn = []() {
    int rValue = std::rand() % 100;
    if (rValue < 50)
    {
        return rValue; //should not return
    }
    std::cout << "   non-return rValue: " << rValue << std::endl;
};
for(int i=0 ; i< 30;i++){
    int rValue= lMayNotReturn();
    std::cout << "random value " << rValue << " ";
    if (rValue >= 50) {
        std::cout << " ???undefined???";
    }
    std::cout << std::endl;
}
std::cout << "end--------" << std::endl;
Run Code Online (Sandbox Code Playgroud)

通过生成的目标gccvisual studio将继续运行并返回随机值作为

 pt@DESKTOP-S54JIQA:/mnt/e/Projects/uv_test$ ./test
   non-return rValue: 83
random value 6295680  ???undefined???
   non-return rValue: 86
random value 6295680  ???undefined???
   non-return rValue: 77
random value 6295680  ???undefined???
Run Code Online (Sandbox Code Playgroud)

像这样的错误比简单的崩溃和铿锵胜利更难追查.

clang不提出我能想到的错误的唯一原因是兼容性.

son*_*yao 5

因为这是未定义的行为.对于退货声明:

在没有返回语句的情况下流出值返回函数(main除外)的结尾是未定义的行为.

这意味着允许编译器做任何事情; 他们不需要给出错误(或不是).