简体   繁体   English

C ++中void和非void函数之间的区别

[英]Difference between void and non-void functions in C++

I have simple question 我有一个简单的问题

Let's say I have two functions in C++: 假设我在C ++中有两个函数:

void DoSomething();

and

bool DoSomething();

Is there any difference in memory or speed between these two functions? 这两个功能之间的内存或速度是否有差异?

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? 因此,将DoSomething()声明为bool对我来说是件好事,以防万一我决定将来返回某些东西?

If your function has no reason to return something, it shouldn't return anything, ie, it should return void . 如果您的函数没有理由返回任何内容,则不应返回任何内容,即应返回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, eg, because it can fail, it should return the corresponding result. 如果您的函数有返回某物的理由,例如,因为它可能失败,则应返回相应的结果。 Since the result will be meaningful, it won't be ignored, ie, 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. 但是,这些注意事项不适用于任何内置类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM