1.对象使用过程中背后调用了哪些方法
需要重点注意几点:
1.C++编译器对于对象构造的优化:用临时对象生成新的对象的时候,临时对象就不产生了,直接构造新对象就可以了,如Test t4 = Test(30, 30) => Test t4(30,30)
2.Test(40,40)
显示生成临时对象 生存周期:所在语句
3.指针引用临时对象出语句会析构(不安全),引用引用临时对象出语句不会析构
4.静态全局变量编译时分配内存,程序启动时初始化。局部静态全局变量编译时分配了内存,第一次运行到初始化
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a = 10, int b = 5) : ma(a), mb(b)
{
cout << "Test(int,int)" << endl;
}
~Test()
{
cout << "~Test()" << endl;
}
Test(const Test &src) : ma(src.ma), mb(src.mb)
{
cout << "Test(const Test&)" << endl;
}
Test &operator=(const Test &src)
{
ma = src.ma;
mb = src.mb;
cout << "operator=" << endl;
return *this;
}
private:
int ma;
int mb;
};
Test t1(10, 10); // 1 Test(int,int)
int main()
{
Test t2(20, 20); // 3 Test(int,int)
Test t3 = t2; // 4 Test(const Test&)
// C++编译器对于对象构造的优化:用临时对象生成新的对象的时候,临时对象就不产生了,直接构造新对象就可以了
// static t4(30,30)
static Test t4 = Test(30, 30); // 5 Test(int,int)
//Test(40,40) 显示生成临时对象 生存周期:所在语句
t2 = Test(40, 40); // 6 Test(int,int) operator= ~Test()
// 显示类型转换 调用构造函数生成临时对象,再赋值
//(50,50)=50 t2 = (Test)50
t2 = (Test)(50, 50); // 7 Test(int,int) operator= ~Test()
// 隐式类型转换 调用构造函数生成临时对象,再赋值
t2 = 60; // 8 Test(int,int) operator= ~Test()
// 指针引用临时对象出语句会析构(不安全) 引用引用临时对象出语句不会析构
Test *p1 = new Test(70, 70); // 9 Test(int,int)
Test *p2 = new Test[2]; // 10 Test(int,int) Test(int,int)
Test *p3 = &Test(80, 80); // Test(int,int) ~Test()
const Test &p4 = Test(90, 90); // Test(int,int)
delete p1; // ~Test()
delete[] p2; //~Test() ~Test()
return 0;
}
Test t5(100, 200); // 2 Test(int,int)
2.调用一个函数,对象调用了哪些方法
重点:被调函数返回一个临时对象时,会首先在调用函数栈帧上拷贝构造一个临时对象(编译器可能会优化这一过程)
#include <iostream>
using namespace std;
class Test
{
public:
Test(int data = 10) : ma(data)
{
cout << "Test(int)" << endl;
}
~Test()
{
cout << "~Test" << endl;
}
Test(const Test &t) : ma(t.ma)
{
cout << "Test(const Test&)" << endl;
}
void operator=(const Test &t)
{
cout << "operator=" << endl;
ma = t.ma;
}
int getData() const { return ma; }
private:
int ma;
};
// 不能返回局部的或者临时对象的指针或引用
Test GetObjectt(Test t) // 3 Test(const Test&)
{
int val = t.getData();
Test tmp(val); // 4 Test(int)
// 返回临时对象 先在main函数栈帧上拷贝构造一个临时对象
return tmp; // 5 Test(const Test&)
} // 6 ~Test ~Test
int main()
{
Test t1; // 1 Test(int)
Test t2; // 2 Test(int)
t2 = GetObjectt(t1); // 7 operator= ~Test(临时对象析构)
return 0;
} // 8 ~Test ~Test
3.对象优化技巧
1.函数传递参数过程中,对象优先引用传递,不要按值传递
2.当函数返回对象的时候,应该优先返回一个临时对象,而不要返回一个定义过的对象
3.接收返回值是对象的函数调用的时候,优先按初始化的方式接收,不要按赋值的方式接收
下面这个需要调用11个函数
优化之后调用4个函数