为什么类中的引用变量总是占用 4 个字节,而不管类型如何?(在 32 位系统上) [英] Why reference variable inside class always taking 4 bytes irrespect of type? (on 32-bit system)

查看:36
本文介绍了为什么类中的引用变量总是占用 4 个字节,而不管类型如何?(在 32 位系统上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,在 32 位 Windows 上运行,visual-studio.

I have below code, running on 32-bit windows, visual-studio.

template <class T>
class Test
{
public:
 T &ref;
 Test(T &x)
  :ref(x)
 {}
};

int main()
{
 cout<<"sizeof Test<int> : "<<sizeof(Test<int>)<<endl;
 cout<<"sizeof Test<double> : "<<sizeof(Test<double>)<<endl;
 cout<<"sizeof Test<char> : "<<sizeof(Test<char>)<<endl;
}

输出为:

sizeof Test<int> : 4
sizeof Test<double> : 4
sizeof Test<char> : 4

编译器为类内的引用变量提供 4 个字节,而不管引用的类型.变量值不能存储在这 4 个字节中.

Compiler giving 4 bytes for reference variable inside class irrespect of the type of reference. Variable value can not be stored in those 4 bytes.

编译器将在这 4 个字节中存储什么信息?

What information compiler will store in those 4 bytes ?

它是否在内部存储引用的地址?这样引用和被指代都可以写入相同的位置以相互同步.

is it internally storing the address of referent? so that reference and referent both can write to the same location to be in sync with each other.

或者它是否在符号表中存储了所指对象的名称?

Or is it storing name of referent in symbol table ?

推荐答案

字节是参考.引用在内部只是一个指针,而指针在 32 位系统上通常使用 4 个字节,与数据类型无关,因为它只是一个地址,而不是值本身.

Those for bytes are the reference. A reference is just a pointer internally, and pointers typically use 4 bytes on a 32bit system, irrespective of the data types because it is just an address, not the value itself.

这篇关于为什么类中的引用变量总是占用 4 个字节,而不管类型如何?(在 32 位系统上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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