加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将一个const引用参数初始化为默认参数会导致悬空引用吗?

发布时间:2020-12-16 04:54:50 所属栏目:百科 来源:网络整理
导读:参见英文答案 What is the lifetime of a default argument temporary bound to a reference parameter?2个 void foo(const std::string s = "abc") { // ...}// ...int main() { // ... foo(); // ...} foo会晃来晃去吗?我认为因为std :: string将从默认值
参见英文答案 > What is the lifetime of a default argument temporary bound to a reference parameter?2个
void foo(const std::string& s = "abc") {
    // ...
}

// ...

int main() {
    // ...
    foo();
    // ...
}

foo会晃来晃去吗?我认为因为std :: string将从默认值“abc”构造,然后这将是一个const引用do death temporary.

我对吗?

解决方法

std :: string(const char *)的构造函数将用于构造一个临时函数,该临时函数将在函数的整个生命周期内生效.

所以没有问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读