C++ 中的形参与返回值

函数调用时,形参对象和返回对象均采用引用方式进行(临时对象作为中介),当一个对象作为参数(非引用)被函数调用时,该对象会通过复制构造函数获得一个临时对象,该临时对象以引用方式传递给函数,简言之,函数会被做以下处理:

void foo(A x);
A a
foo( a);
处理后:
void foo(A& x); A a A x(a); foo(x);

 而返回值则根据不同的函数调用方式来进行不同程度的优化,如下面的调用方式,会直接将对象b作为引用传递给函数bar:

A bar();
A b = bar(); 
//处理后
bar(A& a);
A b;
bar(b);

 如先定义一个对象,编译器就不会对此种情况优化。

A a;
a = bar();//bar函数先产生一个临时对象,再调用赋值构造函数

 完整测试代码如下:

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>

using namespace std;

class A {
 public:
	A() 
	{
		str = (char *)calloc(sizeof(char),10);
		memcpy(str,"hello",5);
		cout << "A()" << endl;
	}

	~A() 
	{
		//delete str;
		cout << "~A()" << endl; 
	}
	
	A(const A& a) 
	{
		cout << "A(const A &a)" << endl;
	}


	A& operator=(const A &a) {
		cout << "A operator=(const A&a)" << endl;
	}

private:
	char *str;
	int len;
};


void foo(A a)
{
	cout << "void foo(A)" << endl;
}

A bar()
{
	A a;
	cout << "A bar()" << endl;
	return a;
}


int main(int argc, char *argv[])
{
	A a;

	// A x(a)
	// foo(&x);
	//foo(a);

	//A b = bar();

	a = bar();

	return 0;
}

 从上面的例子来看,赋值函数、复制构造函数与构造函数地位同等重要。

posted on 2015-07-07 17:40  kkford  阅读(566)  评论(0编辑  收藏  举报

导航