C++中Function里面的call by value 和 call by reference

先来看看C++中call by value的function

void func(int a)
{
    ++a;
}

int main(){

   int a {7};
   func(a);
   cout << format("value is {}\n",a); //a 会输出7

}

c++中call by reference

void func(int* p)
{
    ++*p; // will change the value in its caller
}

int main(){

   int a {7};
   func(&a); //传入的是a的地址
   cout << format("value is {}\n",a);  //a会输出8

}

C++中call by reference更常用的写法是

void func(const int& p)  //引用 best practice是加上const
{
    ++*p; //这里会报错,因为p这个引用是const类型,不能更改
}

int main(){

   int a {7};
   func(a); 
   cout << format("value is {}\n",a);  

}

call by value =>  Internally, values are passed to and from a function, on a small data structure called a stack. The stack is relatively small space, requires processing power to manage.

call by reference => passing large values to a function, requires coping large amounts of data on the stack, this can be time consuming, and it can cause a stack to overflow, which can crash your program and create security volnerabilities. So, when you pass something large than a simple value, you will usually want to use a reference or a pointer

 

函数返回值 Returning value of Func 也是同样的道理,如果返回值是large, 我们也建议使用reference,

#include <format>
#include <iostream>
#include <string>

using std::format;
using std::cout;

const std::string& func(int a) //返回值是个reference type, 用const修饰 这是best practice
{
static std::string s = format("value is {}", a * 2);
return s;
}

int main(){
const auto& x = func(42(;
cout << format("{}\n",x);

}


 

               

       

 

posted on 2022-11-28 13:44  新西兰程序员  阅读(123)  评论(0编辑  收藏  举报