我们可以访问不存在的类类型对象的成员吗? [英] Could we access member of a non-existing class type object?

查看:87
本文介绍了我们可以访问不存在的类类型对象的成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++标准中, [basic.lval]/11.6 说:

In the c++ standard, in [basic.lval]/11.6 says:

如果程序尝试通过以下类型之一以外的glvalue访问对象的存储值,则行为未定义:[...]

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:[...]

  • 一种聚合或联合类型,其元素或非静态数据成员(包括递归地包括子聚合或所包含的联合的元素或非静态数据成员)中包括上述类型之一,[...]

此句子是 strict-aliasing 规则的一部分.

This sentence is part of the strict-aliasing rule.

是否允许我们通过类成员访问来别名?

Does it allow us to alias through class member access?

class A{ //"casted to" aggregate
  int i;
  float g;
  };

int j=10;
int l = reinterpret_cast<A*>(&j)->i;

根据标准,仅当对象接受 lvalue-to-rvalue-conversion

According to the standard, an object value is only accessed if the object is subject to lvalue-to-rvalue-conversion [conv.lval]/2.

[expr.ref] 没有规定对象- expression 必须引用该类型的对象,只是glvalue必须具有类类型( object-expression 是点."左侧的表达式).但是,在与成员访问相关的句子中经常出现一个单词,这可能意味着我忽略了该程序.例如 [expr.ref]/4.1 :

[expr.ref] does not stipulate that the object-expression must refer to an object of that type, only that the glvalue must have class type (the object-expression is the expression at the left of the dot "."). Nevertheless there is a word that recurrently appears in sentence related to member access which may imply constraint on the program that I overlooked. For example [expr.ref]/4.1:

如果E2是静态数据成员,并且E2的类型是T,则E1.E2是一个左值;表达式指定类的命名成员.

指定"是否意味着该成员在其生存期内,并且我不能使用类成员访问perfom别名?还是[basic.lval]/11.6允许?

Could "designates" means that this member is within its lifetime and that I cannot use class member access to perfom aliasing? Or is it allowed by [basic.lval]/11.6?

推荐答案

对于非静态数据成员,该词是:

For non-static data member, the word is:

如果E2是非静态数据成员,并且E1的类型为"cq1 vq1 X",而E2的类型为"cq2 vq2 T",则该表达式指定对象的命名成员由第一个表达式指定.

If E2 is a non-static data member and the type of E1 is "cq1 vq1 X", and the type of E2 is "cq2 vq2 T", the expression designates the named member of the object designated by the first expression.

很显然,由*reinterpret_cast<A*>(&j)指定的对象(即j)没有成员,因此行为是

Clearly the object designated by *reinterpret_cast<A*>(&j), i.e. j, has no member, so the behavior is undefined by omission.

这篇关于我们可以访问不存在的类类型对象的成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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