C++中 string作为参数的传递,传引用,减少内存的拷贝;const参数

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

C++传参尽量不用指针,防止弄乱(引用比指针简单~~)

#include <iostream>
using namespace std;//不要忘记声明变量空间,不然无法使用string类型

void funcA( string& str){
    cout << "传引用 :str = " << str << endl;
    cout << "\"str\" 的地址: " << &str << endl;
}

void funcB(const string str){
    cout << "传值:str = " << str << endl;
    cout << "\"str\"的地址 : " << &str << endl;
}


int main(int agrc, char** argv){
    string strInMain= "test";

    funcA(strInMain);//传引用, 减少内存的拷贝
    funcB(strInMain);//传值,传递的是实参的副本

    cout << "strInMain = " << strInMain << endl;
    cout << "\"strInMain\"在主函数中的地址 : " << &strInMain << endl;
    cout <<strInMain;

    return 0;
}

funA没有拷贝变量,而是直接将main中的strInMain的地址传入,所以在funA中的参数str的地址和main中strInMain的地址相同。因此可以在函数中对字符串修改,传引用。

funB参数对strInMain进行拷贝,所以参数str的地址为新的内存空间,传值

如果不想让函数修改参数的值,只要把参数声明为const常量即可

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