nullptr和指针算法 [英] The nullptr and pointer arithmetic

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

问题描述

考虑以下代码,在nullptr上执行指针算术是否安全?

Considering the following code, is it safe to do pointer arithmetic on nullptr?

我假定将任何偏移量添加到nullptr会导致另一个nullptr,到目前为止,MSVC会按预期产生结果,但是我不确定使用这样的nullptr是否安全:

I assume adding any offsets to a nullptr results in another nullptr, so far MSVC produce results as I expected, however I am a bit unsure about whether using nullptr like this is safe:

float * x = nullptr;

float * y = x + 31; // I assume y is a nullptr after this assigment

if (y != nullptr)
{
  /* do something */
}

推荐答案

您没有定义安全"对您的含义,但是无论如何,您提出的代码都具有不确定的行为.仅对指向数组对象或指向数组一端的指针值允许使用指针算术. (根据此规则,非数组对象被视为一个元素的数组.)

You didn't define what "safe" means to you, but regardless, the code you propose has undefined behaviour. Pointer arithmetic is only allowed on pointer values that point into an array object, or perhaps to one-past-the-end of an array. (Non-array objects are considered an array of one element for the purpose of this rule.)

由于空指针永远不会是一个对象的地址或一个对象的地址,因此您的代码永远不会具有定义明确的行为.

Since the null pointer is never the address of an object or one past an object, your code can never have well-defined behaviour.

这篇关于nullptr和指针算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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