c++ 参数与返回值

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时可能发生拷贝,也可能不发生拷贝。这完全取决于编译器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值