C++中 string作为参数的传递(string类型的引用 )

C++ string作为参数的传递(string类型的引用 )

在传递参数的时候,如果参数是string类型,可以用string类型的引用,减少内存的拷贝。

例如:

void func(const string& para){}
int main(int agrc, char **argv){
	//...
	string str = "test";
	func(test);
	//...
	return 0;
}

测试代码如下:

#include 
#include 

using namespace std;

void func(const std::string& str){
	cout << "str = " << str << endl;
	cout << "address of \"str\" : " << &str << endl; 
}

void funcB(const std::string str){
	cout << "str = " << str << endl;
	cout << "address of \"str\" : " << &str << endl;
}


int main(int agrc, char** argv){
	string strInMain= "test";
	func(strInMain);
	funcB(strInMain);
	
	cout << "strInMain = " << strInMain << endl;
	cout << "address of \"strInMain\" : " << &strInMain << endl;
	
	return 0;
}


C++中 string作为参数的传递(string类型的引用 )_第1张图片
func没有拷贝变量,而是直接将main中的strInMain的地址传入,所以在func中的参数str的地址和main中strInMain的地址相同。
funcB参数对strInMain进行拷贝,所以参数str的地址为新的内存空间

你可能感兴趣的:(C++,计算机系统)