是“一端通过端”非数组类型的指针在C ++中一个有效的概念? [英] Is the "one-past-the-end" pointer of a non-array type a valid concept in C++?

查看:147
本文介绍了是“一端通过端”非数组类型的指针在C ++中一个有效的概念?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准[sec 5.7]说:


如果指针操作数和结果指向同一个数组对象的元素,或者一个过去
数组对象的最后一个元素,评估不会产生溢出;否则,行为是
未定义。


因此,我假设指针one-past-the-end


c $ c> int a = 0;
vector< int> v(& a,(& a)+1);

上述代码段编译和工作正常(使用g ++),但它是有效的吗?

解决方案

不,这是合法的。 5.7(4) - 在你的引号之前的一个段落 - 说:对于这些操作符,指向nonarray对象的指针与指向长度为1的数组的
第一个元素的指针的行为相同,类型的对象作为其元素类型。


The C++ standard [sec 5.7] says:

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

So, am I correct in assuming that pointers one-past-the-end of other types than arrays are undefined?

For example:

int a = 0;
vector<int> v(&a, (&a)+1);

The above snippet compiles and works just fine (with g++), but is it valid?

解决方案

No, it is legal. 5.7(4) - one paragraph before your quote - says: "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type."

这篇关于是“一端通过端”非数组类型的指针在C ++中一个有效的概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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