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

What if I don#39;t put a return value to a function whose prototype returns a value(如果我不给原型返回值的函数添加返回值怎么办)

本文介绍了如果我不给原型返回值的函数添加返回值怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚花了 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++ 是一种自己动手"的语言.

这篇关于如果我不给原型返回值的函数添加返回值怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如果我不给原型返回值的函数添加返回值怎么办

基础教程推荐