如果我不给原型返回值的函数添加返回值怎么办

2022-01-19 00:00:00 return return-value c++

我刚刚花了 3 个小时,可能更多,试图找到一个错误、segfault 或 bad_allow,这取决于我修改代码的方式,以便了解什么对象弄乱了堆栈或内存:我把我所有的对象有疑问...我屠杀了班级...(尽管如此,事实证明这很好,因为这些班级最终发现自己毫无用处:-))...

I have just spend 3 hours, probably more, trying to find a bug, segfault or bad_allow, depending on the way I modified the code so as to understand what object was messing with the stack or memory: I put all my objects in doubt... I slaughtered classes... ( nonetheless this turned out to be good since those classes revealed themselves useless in the end :-) )...

但是,事实上,真正的错误很简单:我没有在应该返回值的函数中编写返回语句(在我的例子中,我需要返回一个 std::vector<boost::any>).

But, indeed, the real mistake was simply: I hadn't written a return statement in a function that should return a value (in my case I needed to return a std::vector<boost::any>).

我认为没有它就无法编译 gcc (4.6.3).当我想起 ms visual 2010 也发生了类似的事情时,我感到更加陌生.

I thought that gcc (4.6.3) couldn't have compiled without it. And I feel even stranger remembering that something similar has happened to me with ms visual 2010.

所以现在我想知道不写退货声明是否合法?在这种情况下会发生什么?

So now I am wondering whether it is legal not to write a return statement ?? What happens in such cases ?

是否与 main 可以有返回值的事实有关?或者我应该考虑使用 gcc 4.7 吗?

Is it related with the fact that the main that can have a return value or not ? Or should I consider going to gcc 4.7 ?

推荐答案

这是未定义的行为:

[C++11: 6.6.3/2]: [..] 从函数的末尾流出相当于 return 没有价值;这会在返回值的函数中导致未定义的行为.

[C++11: 6.6.3/2]: [..] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

编译是因为:

  1. 编译器不需要对其进行诊断;
  2. 诊断这并不总是微不足道的,因此您的编译器不会打扰;
  3. C++ 是一种自己动手"的语言.

相关文章