c++ - 完整对象还是子对象?

标签 c++ c++14 language-lawyer

C++14 标准说:

A subobject can be a member subobject, a base class subobject, or an array element. An object that is not subobject of any other object is called a complete object. (§1.8(2))

对我来说,“可以”是否意味着隐含的“当且仅当”并不明显。举个例子,在下面的代码片段中,r 是对完整对象还是子对象的引用?

#include <iostream>
int main(){
  int i=2;
  unsigned char & r=reinterpret_cast<unsigned char&>(i);
  std::cout<<(int)r<<"\n";  
}

由于 r 引用对象表示中的 unsigned char,因此 r 应该引用一个对象:

The object representation of an object of type T is the sequence of N unsigned char objects taken up by the object of type T, ... (§3.9(4))


编辑:请您非常清楚 i 的第一个字节是什么: 1)根本没有任何物体, 2)一个完整的对象, 3) 子对象

只有这三种可能。

最佳答案

该句子将术语子对象定义为以下之一:成员子对象基类子对象或数组元素。

您的代码片段与子对象无关。 r 是一个引用,而不是一个对象。此外,它甚至不引用对象,它只是为 i 的第一个字节添加别名。

来自[intro.object]:

An object is created by a definition (3.1), by a new-expression (5.3.4), when implicitly changing the active member of a union (9.3), or when a temporary object is created (4.4, 12.2).

i 是由定义创建的对象。由于 int 不是类或数组类型,因此它没有子对象。对象表示,即构成 i 存储的底层无符号字符数组,不是对象 - 它不是在上述任何上下文中创建的。定义对象表示的措辞是core issue 1701的主题。 (h/t T.C.)。

关于c++ - 完整对象还是子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40108184/

相关文章:

c++ - 迭代顶点缓冲区

c++ - char 数组的严格别名和并集

c++ - Linphone 编译 - Mingw 64 位 - 未找到 GNU gettext 工具;国际工具所需

c++ - 如何将 webrtc 原生 api 添加到我的 qt 项目中?

c++ - 为参数顺序不同的模板类创建比较特征

c++ - "Ambiguous base class"模板上下文错误

c++ - 检查方法的模板特化是否存在

c++ - 严格别名规则是否适用于函数调用?

c++ - init-declarators 的完整表达式的定义

c++ - constexpr 函数必须有一个参数值?