问题1:什么是指针值?
A value of a pointer type that is a pointer to or past the end of an object represents the address of the first byte in memory ([intro.memory]) occupied by the object54 or the first byte in memory after the end of the storage occupied by the object, respectively.
这是否意味着指针值是对象的地址?
问题2:如何理解**指针值不变**?
[expr.static.cast]/13
Otherwise, if the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.
考虑以下示例:
#include <iostream>
int main(){
int a = 0;
void* tmp = &a;
char* obj = static_cast<char*>(tmp);
}
根据上面的引用,我们知道tmp
的原始指针值指向a
,目标指针值指向char类型的对象,因为它们不是指针可互换的,因此句子不变指针值通过转换起作用。这是否意味着obj
现在是指向char
类型的对象的指针,而该对象的动态类型是int
,如果我误解了pointer value is unchanged
,这句话是什么意思?问题3:如何理解
the result is a pointer to b
。#include <iostream>
struct Data{
int c;
}
int main(){
Data d;
void* tmp2 = &d;
int* ptr = static_cast<int*>(tmp2);
}
我们知道tmp2
的原始指针值指向d
,因此原始指针值指向Data
类型的对象,而目标指针指向int
类型的对象,并且这两个对象是指针可互换的,因此这句话the result is a pointer to b
起作用了。这是否意味着现在指向ptr
类型的对象的int
指针和该对象的动态类型也是int
?
最佳答案
A value of a pointer type that is a pointer to or past the end of an object represents the address of the first byte in memory ([intro.memory]) occupied by the object or the first byte in memory after the end of the storage occupied by the object, respectively.
这是否意味着指针值是对象的地址?
没有。
该句子结构“A或B分别表示X或Y”被理解为“条件A表示X,或者条件B表示Y”。
所以这句话的意思是
A value of a pointer type that is a pointer to an object represents the address of the first byte in memory ([intro.memory]) occupied by the object ...
和
A value of a pointer type that is a pointer past the end of an object represents the address of the first byte in memory after the end of the storage occupied by the object.
分别允许作者在重复这样的扩展时,删除重复的序言。
而且,毕竟,即使是第一种情况,您的意思也不太正确。
这意味着指针(如果是指向对象的指针)表示对象在内存中第一个字节的地址。除非它是指向对象的指针,否则它不会对任何指针的值进行任何说明。
这并不意味着每个指针值都是一个对象的地址,因为指针可以是未初始化的,也可以设置为nullptr
,或者设置为原始分配的结果,该原始分配尚未转换为放置new
的对象。指针也仍然可以通过该指针保存刚刚delete
-d的对象的地址。
我知道该标准不是很容易阅读,特别是如果您不习惯这种风格(或英语)的话-但这意味着您需要付出一些努力才能仔细阅读它。
关于c++ - 关于对象指针的一些困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61227319/