c++ - c++中引用变量的内存?

标签 c++

我刚开始从基础学习 Cpp,当我遇到引用变量时感到困惑。

据我所知,引用变量就像一个别名(同一内存的另一个名称),因此在这种情况下它需要任何内存。

当我运行下面的代码时:

class sample_class
{
    public:
        int num; //line1
        int& refnum = num; //line2
}

int main()
{
    sample_class sample_object;
    cout<< "sample_class object size : " << sizeof(sample_object) <<endl;
    return 0;
}

我得到的输出是:

sample_class object size : 8

==>此处,num 的大小为 4 字节(32 位编译器)和 refnum,因为引用只是 num< 的别名。那么,为什么在这种情况下,对象的大小是 8

==>此外,如果真的 refnum 就像一个别名那么这个信息什么时候( refnum 也保存/别名到 的相同内存地址的信息code>num) 被存储?

已编辑:

并考虑这种情况(更改 sample_class 的定义):

class sample_class
{
    public:
        char letter; //line3
        char& refletter = letter; //line4
        char letter_two; //line5
}

在这里,如果我打印 sample_class 对象的对象大小,我得到它作为 12(尽管 letter 的大小,refletterletter_two 都等于 1)。但是如果我注释 第 4 行,则对象大小仅为 2这是怎么回事???

我有兴趣从基础学习,所以如果我有任何错误,请纠正我

最佳答案

引用是别名,不应将其视为新变量。您无法获取其地址,也无法获取其大小。任何这样做的尝试都将改为获取别名对象的地址或大小。实际上,大多数实现都像指针一样实现它们,但标准并不要求这样做。它没有提及引用的预期大小。

发件人:http://en.cppreference.com/w/cpp/language/reference

References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics (e.g. a non-static data member of reference type usually increases the size of the class by the amount necessary to store a memory address).

编辑:C++ 标准为实现提供了很大的回旋余地,可以自行决定类型和类的大小,以适应每种体系结构的独特要求。在这种情况下,会在您的类(class)成员之间引入填充。 C++ 中没有要求类的大小必须等于其成员大小的总和。参见 Objects and alignment在 cppreference.com 上获取有关该主题的更多信息。

编辑 2:关于 sizeof(T&) 似乎仍然存在一些混淆。

来自 http://en.cppreference.com/w/cpp/language/sizeof :

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

表达式 sizeof(T&) 被视为您编写了 sizeof(T)。这并不意味着 T& 的大小等于 T 的大小。只是您无法直接使用 sizeof 获取引用的大小。

关于c++ - c++中引用变量的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44027732/

相关文章:

c++ - 为什么在段错误中通过 B 类中的方法初始化 A 类的指针?

C++ 随机数逻辑运算符奇怪的结果

c++ - LLVM IR 生成的代码到 native 代码

c++ - 无法在Visual Studio中的Bash中运行文件

c++ - 如何在 C++ 中查找可变类型列表的所有组合

html - C++:如何从网站 HTML 中提取多个 URL 到一个 vector 中?

c++ - 跳过for循环,为什么?

c++ - 从 vector 中删除元素

c++ - 当有指向其中其他对象的指针时创建对象数组

c++ - Qt嵌入式Linux事件观察器