本文介绍了T *与char *指针算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含N个类型为T的元素的数组.

Assume we have an array that contains N elements of type T.

T a[N];

根据C ++ 14标准,在这种情况下,我们可以保证

According to the C++14 Standard, under which conditions do we have a guarantee that

 (char*)(void*)&a[0] + n*sizeof(T) == (char*)(void*)&a[n],  (0<=n<N) ?

尽管对于许多类型和实现都是如此,但该标准在脚注中并以一种含糊的方式提及了这一点:

While this is true for many types and implementations, the standard mentions it in a footnote, and in an ambiguous way:

几乎没有迹象表明其他方式被认为等同于标准方式.对于实施者而言,它可能暗示了许多一致的实施中的一种.

There is little indication that this other way was thought of being equivalent to the standard's way. It might rather be a hint for implementers that suggests one of many conforming implementations.

人们低估了这个问题的难度.

People have underestimated the difficulty of this question.

这个问题不是关于您在教科书中可以读到的内容,而是关于您可以通过使用逻辑和理由从C ++ 14标准中得出什么.

This question is not about what you can read in textbooks, it is about what what you can deduce from the C++14 Standard through the use of logic and reason.

如果您使用连续"或连续",还请说出连续的内容.

If you use 'contiguous' or 'contiguously', please also say what is being contiguous.

虽然T []和T *密切相关,但是它们是抽象的,并且T * x N上的加法可以由实现以任何一致的方式定义.

While T[] and T* are closely related, they are abstractions, and the addition on T* x N may be defined by the implementation in any consistent way.

使用指针加法重新排列了方程式.如果p指向char,则始终使用(§5.7(4))或一元加法来定义p + 1,因此我们不会遇到UB.原始文件包含指针减法,这可能早早导致了UB. (只比较char指针,不取消引用).

The equation was rearranged using pointer addition. If p points to a char, p+1 is always defined using (§5.7 (4)) or unary addition, so we don't run into UB. The original included a pointer subtraction, which might have caused UB early on. (The char pointers are only compared, not dereferenced).

推荐答案

在[dcl.array]中:

In [dcl.array]:

连续表示T类型的任何连续子对象之间的偏移为sizeof(T),这表示第n个子对象的偏移为n*sizeof(T).

Contiguous implies that the offset between any consecutive subobjects of type T is sizeof(T), which implies that the offset of the nth subobject is n*sizeof(T).

n < N的上限来自[expr.add]:

The upper bound of n < N comes from [expr.add]:

这篇关于T *与char *指针算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:44