简体   繁体   English

这个返回值的目的是什么?

[英]What is the purpose of this return value?

I ran into some code I couldn't find an answer to on Google or SO.我遇到了一些在 Google 或 SO 上找不到答案的代码。 I am looking at a thread function which returns void* as you could expect.我正在查看一个线程 function 如您所料返回 void* 。 However, before the thread function ends it suddenly pulls this stunt,然而,在线程 function 结束之前,它突然拉了这个噱头,

return (void*) 0;

What is the purpose of that?这样做的目的是什么? I can't make any sense of it.我无法理解它。

edit:编辑:

After understanding this is the same as NULL-- it is my thought they used this to skip including stdlib.在理解这与 NULL 相同之后——我认为他们使用它来跳过包括 stdlib。

(void*)0 is the null pointer, aka NULL (which actually is a macro defined in several header files, eg stddef.h or stdio.h , that basically amounts to the same thing as (void*)0 ). (void*)0是 null 指针,又名NULL (实际上是在几个 header 文件中定义的宏,例如) stddef.hstdio.h基本相同的东西(void*)0 h)

Update:更新:

How to explain null pointers and their usefulness?如何解释 null 指针及其用处? Basically, it's a special value that says, "This pointer doesn't point anywhere," or, "This pointer is not set to a valid object reference."基本上,它是一个特殊值,表示“此指针未指向任何位置”或“此指针未设置为有效的 object 引用”。

Historical note: Tony Hoare, who is said to have invented null references in 1965, is known to regret that invention and thus calls it his "Billion Dollar Mistake" :历史记录:据说托尼·霍尔在 1965 年发明了 null 参考文献,众所周知,他对这项发明感到遗憾,因此称其为“十亿美元的错误”

Whenever you work with pointers, you must make sure to never dereference a null pointer (because it doesn't reference anything by definition).无论何时使用指针,都必须确保永远不要取消引用 null 指针(因为它没有根据定义引用任何内容)。 If you do it anyway, you'll either get abnormal program termination, a general protection fault, or unexpected program behaviour at the very least.如果你仍然这样做,至少你会得到异常的程序终止、一般的保护错误或意外的程序行为。

Well, I have not encountered any C++ compiler saying NULL or 0 cannot be converted to void* (or to/from int* , for example).好吧,我还没有遇到任何 C++ 编译器说NULL0不能转换为void* (或 to/from int* ,例如)。 But there might be some smart compilers or static-analysis tools that would report 0 to void-pointer conversion as a warning.但是可能有一些智能编译器或静态分析工具会报告0 to void-pointer转换作为警告。

That statement is commonly found in callback implementation (like a thread-routine), which must adhere to prototype of callback being demanded ( pthread_create , CreateThread etc).该语句通常在回调实现(如线程例程)中找到,它必须遵守所要求的回调原型( pthread_createCreateThread等)。 Therefore, when you implement that function, you must return the same type it was demanded for.因此,当您实现 function 时,您必须返回所需的相同类型。 For pthread_create routine , you must return a void* - and that's why return (void*)0;对于pthread_create例程,您必须返回一个void* - 这就是为什么return (void*)0; is there.在那儿。

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

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