简体   繁体   中英

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 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.

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.

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.

In the context of std::thread , you should specify it as 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* . 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. The idiomatic C++ API in std is type aware. So void it is. And if you do care about return values, have a look at std::future .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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