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   新西兰程序员  阅读(130)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2016-11-28 Web安全之XSS
2016-11-28 Session和Cookie的分析与区别
2016-11-28 Client Dependency学习
2016-11-28 DMOZ介绍以及如何提交
2013-11-28 转载MVC Html.AntiForgeryToken() 防止CSRF攻击
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示