简体   繁体   English

C++ - 在线程中使用时将函数的返回值声明为 void/void* 有区别吗?

[英]C++ - Is there a difference between declaring a function's return value as void/void* when used in a thread?

Is there a difference between declaring a function's return value as void/void* in case it's used with std::thread ?将函数的返回值声明为 void/void* 与std::thread一起使用是否有区别?

void encrypt(/*arguments*/)
{
}

// ...

std::thread(encrypt, /*arguments*/);

I read something about using void* when working with threads so I wanted to make sure I'm using void and not void* for a good reason.我读了一些关于在处理线程时使用void* ,所以我想确保我使用的是void而不是void*有充分的理由。

Yes there is.就在这里。 For instance this function:例如这个函数:

void func() {  }

Is well formed.形成良好。 On the other hand, this one:另一方面,这个:

void* func() {  }

Violates a language constraint, and is ill-formed.违反语言限制,并且格式错误。 The difference?区别? You can't omit the return statement, or your program will have undefined behavior.您不能省略 return 语句,否则您的程序将具有未定义的行为。

void in this case specifies a lack of a return type, but void* is a complete type, and therefore you must specify a value for the function to return.在这种情况下, void指定缺少返回类型,但void*是完整类型,因此您必须指定要返回的函数的值。

In the context of std::thread , you should specify it as void .std::thread的上下文中,您应该将其指定为void Any return value is ignored anyway, so just keep your program well formed without returning something meaningless just for the sake of it.无论如何,任何返回值都会被忽略,所以只要保持程序的格式良好,不要仅仅为了它而返回无意义的东西。

If you read about Pthreads online, by any chance, then they do expect a callback that both accepts and returns void* .如果您在网上阅读有关 Pthreads 的任何信息,那么他们确实希望有一个既接受又返回void*的回调。 That is so they could support any parameter and any return type .这样它们就可以支持任何参数任何返回类型 But that's a C API, so it has to do it like this.但那是一个 C API,所以它必须这样做。 The idiomatic C++ API in std is type aware. std惯用的 C++ API 是类型感知的。 So void it is.所以它是void的。 And if you do care about return values, have a look at std::future .如果您确实关心返回值,请查看std::future

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

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