本帖最后由 lrj2025kernel 于 2026-8-26 11:48 编辑
一、演示代码
[C++] 纯文本查看 复制代码 #include "stdio.h"
/* ===================================================================
* [日期]: 2026年8月26日11时33分15秒
* [功能]: 追踪类成员变量生命周期
* =================================================================== */
class Trace {
public:
Trace(const char* name) :m_name(name) {
printf("%s\n", m_name);
}
~Trace() {
printf("%s\n", m_name);
}
private:
const char* m_name;
};
class CPerson {
public:
CPerson():pid("CPerson::pid") {
printf("%s\n", "CPerson::CPerson()");
}
virtual ~CPerson() {
printf("%s\n", "CPerson::~CPerson()");
}
private:
Trace pid;
};
class Lesson {
public:
Lesson():count("Lesson::count")
{
printf("%s\n", "Lesson::Lesson()");
}
~Lesson()
{
printf("%s\n", "Lesson::~Lesson()");
}
private:
Trace count;
};
class CStudent : public CPerson {
public:
CStudent() :weight("CStudent::weight"), height("CStudent::height")
{
printf("%s\n", "CStudent::CStudent()");
}
~CStudent()
{
printf("%s\n", "CStudent::~CStudent()");
};
private:
Trace height;
Trace weight;
Lesson lesson;
};
int main(int argc, char* argv[]) {
{
CStudent one;
}
return 0;
}
二、运行结果
三、注意事项
1、即便CPerson类中的成员pid是私有成员,CStudent one;执行完毕后的子类CStudent内存模型中包含它,私有只是代码不能类外部访问(one->pid编译错误)并不代表子类内存模型中没有它,通过偏移仍可访问到
2、内存模型中成员排布顺序与类成员变量声明顺序一致,与初始化列表中的出现先后顺序无关 |