You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向函数传递string时,为何使用const std::string&而非string?

向函数传递字符串:值传递 vs const引用传递

先说明:你的代码1存在语法错误(函数和main的括号书写错误),修正后才能正常运行,下面重点讲两种传递方式的核心区别:

1. 值传递(代码1的方式)

当参数写成string phrase_to_print时,调用printPhrase(phrase)会发生这些行为:

  • 把主函数里的phrase完整复制一份,生成一个新的字符串对象,函数内部操作的都是这个副本
  • 内存与性能开销:字符串越长,复制所需的内存和时间越多,函数执行完还要销毁这个副本,完全是不必要的资源浪费
  • 这种方式唯一的“好处”是函数里随便修改副本都不会影响原字符串,但你的场景只是打印,完全用不上这个特性

2. const引用传递(代码2的方式)

参数里的&和const各有明确作用:

  • &是引用:相当于给原字符串phrase起了个别名phrase_to_print,函数直接操作原对象的内存,不会产生复制行为,彻底避免了上面提到的内存与性能浪费,处理长字符串时优势尤其明显
  • const是只读约束:告诉编译器这个引用只能读取不能修改,如果函数里不小心写了修改phrase_to_print的代码(比如phrase_to_print = "new text"),编译器会直接报错,从语法层面保证原字符串不会被意外修改,提升了代码安全性

对你疑问的解答

不止是内存影响:

  • &主要解决的是内存开销与性能问题,消除不必要的复制操作
  • const解决的是代码安全性问题,防止函数误改原数据

修正后的代码1

#include <iostream>
using namespace std;

void printPhrase(string phrase_to_print){
    cout << phrase_to_print << endl;
}

int main(){
    std::string phrase = "This is my phrase";
    printPhrase(phrase);
    return 0;
}

代码2(正确可运行)

#include <iostream>
using namespace std;

void printPhrase(const std::string& phrase_to_print){
    cout << phrase_to_print << endl;
}

int main(){
    std::string phrase = "This is my phrase";
    printPhrase(phrase);
    return 0;
}

内容的提问来源于stack exchange,提问作者teeeeee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 13:25:19