0
点赞
收藏
分享

微信扫一扫

C++ | C++对象的内存模型


C++ | C++对象的内存模型

类是创建对象的模板,不占用内存空间,不存在于编译后的可执行文件中;而对象是实实在在的数据,需要内存来存储。
对象被创建时会在栈区或者堆区分配内存

编译器会将成员变量和成员函数分开存储:分别为每个对象的成员变量分配内存,但是所有对象都共享同一段函数代码。如下图所示:

C++ | C++对象的内存模型_创建对象

实例1:

/*******************************************************************
 *   > File Name: classStudent.cpp
 *   > Create Time: 2021年09月 9日  9:36:25
 ******************************************************************/
#include <iostream>
#include <cstring>
using namespace std;

class Student{
private:
    char *m_name; /* 成员变量 */
    int  m_age; /* 成员变量 */
    float m_score; /* 成员变量 */
public:
    void setName(const char *name); /* 成员函数声明 */
    void setAge(int age); /* 成员函数声明 */
    void setScore(float score); /* 成员函数声明 */
    void show(void); /* 成员函数声明 */
};

/* 定义成员函数 */
void Student::setName(const char *name)
{
    strcpy(m_name, name);
}

void Student::setAge(int age)
{
    m_age = age;
}

void Student::setScore(float score)
{
    m_score = score;
}

void Student::show(void)
{
    cout << "Name: " << m_name << endl;
    cout << "Age: " << m_age << endl;
    cout << "Score: " << m_score << endl;
}

int main(void)
{
    /* 在栈上创建对象 */
    Student stu1;
    cout << "sizeof(stu1): " << sizeof(stu1) << endl;

    /* 在堆上创建对象 */
    Student *pstu2;
    pstu2 = new Student(); 
    cout << "sizeof(pstu2): " << sizeof(pstu2) << endl;  
    cout << "sizeof(*pstu2): " << sizeof(*pstu2) << endl;

    /* 类的大小 */
    cout << "sizeof(Student): " << sizeof(Student) << endl;

    cout << "=================" << endl;
    cout << "sizeof(char*): " << sizeof(char*) << endl;
    cout << "sizeof(int): " << sizeof(int) << endl;
    cout << "sizeof(float): " << sizeof(float) << endl;

    return 0;
}

编译、运行:

PS E:\fly-prj\cplusplus\day9> make 
g++ -o classStudent classStudent.cpp -g -Wall
PS E:\fly-prj\cplusplus\day9> .\classStudent.exe
sizeof(stu1): 16
sizeof(pstu2): 8
sizeof(*pstu2): 16
sizeof(Student): 16
=================
sizeof(char*): 8
sizeof(int): 4
sizeof(float): 4

类可以看做是一种复杂的数据类型,也可以使用 sizeof 求得该类型的大小。
从运行结果可以看出,在计算类这种类型的大小时,只计算了成员变量的大小,并没有把成员函数也包含在内。

假设 stu1 的起始地址为 0X1000,那么该对象的内存分布如下图所示:

C++ | C++对象的内存模型_成员变量_02

m_name、m_age、m_score 按照声明的顺序依次排列,和结构体非常类似,也会有内存对齐的问题。


举报

相关推荐

0 条评论