1.参数
函数执行的第一步就是隐式的定义初始化形参。如果直接进行值传递,此处会发生拷贝构造。
void func(int val)
{
}
//优化传递值的方法
//1.避免拷贝使用指针
//2.避免拷贝使用引用值
//在使用这两种方法减少数值拷贝的时候应该注意const的权限控制
int main()
{
func(5);//在调用函数时,传入参数隐式的发生了int val = 5;
return 0;
}
2.返回值
2.1在返回值处,也发生着隐式的拷贝
class test
{
public:
test() :m_a(0) { cout << "无参构造" << endl; }
test(int a) :m_a(a) { cout << "有参构造 " << endl; }
test(const test& that) :m_a(that.m_a) { cout << "拷贝构造" << endl; }
test(test&& that) { m_a = that.m_a; cout << "右值构造" << endl;}
private:
int m_a;
};
test func(int a)
{
test c = test(a);//有参构造
return c;//发生test(c)拷贝构造
}
int main()
{
func(2);
return 0;
}
2.2思考
class test
{
public:
test() :m_a(0) { cout << "无参构造" << endl; }
test(int a) :m_a(a) { cout << "有参构造 " << endl; }
test(const test& that) :m_a(that.m_a) { cout << "拷贝构造" << endl; }
test(test&& that) { m_a = that.m_a; cout << "右值构造" << endl;}
private:
int m_a;
};
test func(int a)
{
test c = test(a);//有参构造
return c;//发生test(c)拷贝构造
}
int main()
{
test a = func(2);//使用func(2)初始化a时什么也没发生?
return 0;
}
而如果此时接受返回值,结果依旧不变。
那是否可以确定使用func(2)初始化a时什么也没发生呢?
3.参考
查看C++ 提高性能手段 —— 临时对象的产生与避免 - 简书 (jianshu.com)时发现,这个是和编译器有关的。
也就是说构造test a时可能发生拷贝,也可能不发生拷贝。这完全取决于编译器。