非 void 函数上的 C++ 崩溃没有 return 语句

C++ Crash on a non-void function doesn't have return statement

当像这样的非 void 函数没有 return 任何东西时,我遇到了崩溃:

#include <iostream>

    class ClassA {
    public:
        bool foo();
        void foo2();
    };
    bool ClassA::foo() {
        int var1 = 100;
        var1++; 
    }
    
    void ClassA::foo2() {
       foo();
    }
    
    int main() {
       ClassA a;
       a.foo2();
       printf("end of code");
       return 0;
    }

请注意,return 类型的 foo() 是 bool,但实现不会 return 任何东西。崩溃在 Android NDK 版本 r19 上可 100% 重现。

同样的代码在 NDK-r15c 上也能正常工作。

你是invoking Undefined Behavior:

If a function is declared to return a value, and fails to do so, the result is undefined behavior (in C++). One possible result is seeming to work, which is pretty much what you're seeing here.

I got a crash when a non void function like this didn't return anything:

因为这是未定义的行为。

C++20 标准草案的§8.6.3:

flowing off the end of a [non-void] function other than main results in undefined behavior.

请注意,这与函数的实际调用方式无关。因此,即使 return 值被忽略(如 OP 的情况),也是导致 UB 的 "flowing off the end"。

你的程序总是出错。

函数 必须 有一个 return,你的编译器应该已经警告过你了。

在 C++ 中,是否在调用点使用结果值是无关紧要的(尽管在 C 中并非如此)。

只是您对以前的工具链感到不走运,恰好 生成的代码恰好 不会导致崩溃作为其症状。那很不吉利,因为它会提示您当时更正错误。