void* 如何作为通用引用类型工作? [英] How does void* work as a universal reference type?

查看:35
本文介绍了void* 如何作为通用引用类型工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自编程语言语用学,作者 Scott

From Programming Language Pragmatics, by Scott

用于系统编程,或者为了方便编写通用容器(集合)对象(列表、堆栈、队列、集合等)保存对其他对象的引用,几个语言提供了一个通用的引用类型.在 C 和 C++ 中,这类型称为 void *.在 Clu 中,它被称为 any;在 Modula-2 中,地址;在 Modula-3 中,refany;在 Java 中,对象;在 C# 中,对象.

For systems programming, or to facilitate the writing of general-purpose con- tainer (collection) objects (lists, stacks, queues, sets, etc.) that hold references to other objects, several languages provide a universal reference type. In C and C++, this type is called void *. In Clu it is called any; in Modula-2, address; in Modula-3, refany; in Java, Object; in C#, object.

在 C 和 C++ 中,void * 如何作为通用引用类型工作?

In C and C++, how does void * work as a universal reference type?

void * 始终只是一个指针类型,而通用引用类型包含所有值,包括指针和非指针.所以我看不出 void * 是一个通用引用类型.

void * is always only a pointer type, while a universal reference type contains all values, both pointers and nonpointers. So I can't see how void * is a universal reference type.

谢谢.

推荐答案

void* 指针通常会保存任何不是 C++ 成员指针的指针.这在实践中相当不方便,因为您需要先将其转换为另一种指针类型,然后才能使用它.您还需要将其转换为与 from 转换时相同的指针类型,以使 void* 成为可能,否则您可能会面临未定义行为的风险.

A void* pointer will generally hold any pointer that is not a C++ pointer-to-member. It's rather inconvenient in practice, since you need to cast it to another pointer type before you can use it. You also need to convert it to the same pointer type that it was converted from to make the void*, otherwise you risk undefined behavior.

一个很好的例子是 qsort 函数.它需要一个 void* 指针作为参数,这意味着它可以指向任何数组.您传递给 qsort 的比较函数必须知道如何将两个 void* 指针转换回数组元素的类型,以便对它们进行比较.

A good example would be the qsort function. It takes a void* pointer as a parameter, meaning it can point to an array of anything. The comparison function you pass to qsort must know how to cast two void* pointers back to the types of the array elements in order to compare them.

这篇关于void* 如何作为通用引用类型工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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