C ++中void和非void函数之间的区别 [英] Difference between void and non-void functions in C++

查看:192
本文介绍了C ++中void和非void函数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题

假设我在C ++中有两个函数:

Let's say I have two functions in C++:

void DoSomething();

bool DoSomething();

这两个功能之间的内存或速度是否有差异?

Is there any difference in memory or speed between these two functions?

第二个问题,与第一个问题相关:我认为存在速度差异,因为布尔必须返回一些值.但是我根本不需要使用返回值.因此,将DoSomething()声明为bool对我来说是件好事,以防万一我决定将来返回某些东西?

And second question, related to first: I suppose that there is speed difference, as bool has to return some value. But I don't have to use return value at all. So, would it be good for me to declare DoSomething() as bool, just in case I decided to return something in the future?

推荐答案

如果您的函数没有理由返回任何内容,则不应返回任何内容,即应返回void.给出一个不会产生任何结果的人为的返回值是没有意义的.

If your function has no reason to return something, it shouldn't return anything, i.e., it should return void. There is no point in giving a function which doesn't produce any result an artificial return value.

如果您的函数有理由返回某些内容,例如由于可能失败,则应返回相应的结果.由于结果将是有意义的,因此将不会被忽略,即没有不返回值的优化潜力.

If you function has a reason to return something, e.g., because it can fail, it should return the corresponding result. Since the result will be meaningful, it won't be ignored, i.e., there is no optimization potential for not returning value.

事情变得有趣的地方是返回大型对象时:可能发生的潜在复制可能会很昂贵,并且在重用内存方面也有速度优势.但是,这些注意事项不适用于任何内置类型.

Where things do become interesting is when returning massive objects: the potential copy happening may be expensive and there is also a speed advantage with respect to reusing memory. However, these considerations don't apply to any of built-in types.

这篇关于C ++中void和非void函数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆