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

将const std::string& str = ""作为构造函数默认参数是否安全?

这种写法完全安全

这里的""是C风格字符串字面量,会被隐式转换成临时的std::string对象。C++标准允许const左值引用绑定到临时对象,并且该临时对象的生命周期会被延长到引用的作用域结束——也就是整个构造函数调用的全过程。

在你的构造函数中,只是将这个临时std::string的值赋值给成员变量str,整个过程不存在未定义行为,完全符合C++标准,可以放心使用。

顺带提个优化建议:可以把构造函数改成成员初始化列表的形式,效率会更高:

struct StrHolder {
    std::string str;

    StrHolder(const std::string& _str = "") : str(_str) {}
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:22:01