为什么sizeof一个引用类型给你的sizeof类型? [英] Why does sizeof a reference type give you the sizeof the type?

查看:682
本文介绍了为什么sizeof一个引用类型给你的sizeof类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标准,在[expr.sizeof](5.3.3.2)中,我们得到:

According to the standard, in [expr.sizeof] (5.3.3.2) we get:


一个引用类型,结果是引用类型的大小。

When applied to a reference or a reference type, the result is the size of the referenced type.

这似乎与引用未指定的事实一致[ dcl.ref](8.3.2.4):

This seems to go along with the fact that references are unspecified [dcl.ref] (8.3.2.4):


未指定参考是否需要存储

It is unspecified whether or not a reference requires storage

但是对我来说,在这种语言中有这样的不一致性似乎很奇怪。无论参考是否需要存储,是否能够确定参考使用多大的大小并不重要?看到这些结果似乎是错误的:

But it seems pretty strange to me to have this kind of inconsistency within the language. Regardless of whether or not the reference requires storage, wouldn't it be important to be able to determine how much size the reference uses? Seeing these results just seems wrong:

sizeof(vector<int>) == 24
sizeof(vector<int>*) == 8
sizeof(vector<int>&) == 24
sizeof(reference_wrapper<vector<int>>) == 8

想要 sizeof(T&)== sizeof(T)定义?

推荐答案

选择有点武断,试图完全证明两个选项都会导致循环的形而上学的参数。

The choice is somewhat arbitrary, and trying to fully justify either option will lead to circular metaphysical arguments.

引用的意图是对象本身的(别名)

The intent of a reference is to be (an alias for) the object itself; under that reasoning it makes sense for them both to have the same size (and address), and that is what the language specifies.

抽象是泄漏的 - 有时候是一个参考有自己的存储,独立于对象 - 导致异常,像那些你指出。但是,当我们需要处理一个引用作为对象的单独实体时,我们有指针。

The abstraction is leaky - sometimes a reference has its own storage, separate from the object - leading to anomolies like those you point out. But we have pointers for when we need to deal with a "reference" as a separate entity to the object.

这篇关于为什么sizeof一个引用类型给你的sizeof类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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