源代码1:
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "In A(): " << hex << (long)this << endl;
}
A(const A&)
{
cout << "In A(const A&): " << hex << (long)this << endl;
}
~A()
{
cout << "In ~A(): " << hex << (long)this << endl;
}
A& operator=(const A& a)
{
cout << "In operator=: " << hex << (long)this << " = " << hex << (long)(&a) << endl;
return *this;
}
};
A f()
{
A a;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a = f();
return 0;
}

源代码2:
// test1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "In A(): " << hex << (long)this << endl;
}
A(const A&)
{
cout << "In A(const A&): " << hex << (long)this << endl;
}
~A()
{
cout << "In ~A(): " << hex << (long)this << endl;
}
A& operator=(const A& a)
{
cout << "In operator=: " << hex << (long)this << " = " << hex << (long)(&a) << endl;
return *this;
}
};
A f()
{
A a;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
A a=f();
return 0;
}

本文通过两个C++源代码示例详细解析了类的构造函数、拷贝构造函数、析构函数及赋值操作符在不同场景下的调用流程与执行顺序。有助于理解对象生命周期及内存管理。
3440

被折叠的 条评论
为什么被折叠?



