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);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!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攻击