gpt4 book ai didi

c++ - 可以通过 const 引用返回默认参数的值吗?

转载 作者:行者123 更新时间:2023-12-02 03:29:20 24 4
gpt4 key购买 nike

是否可以通过 const 引用返回默认参数的值,如下例所示:

https://coliru.stacked-crooked.com/a/ff76e060a007723b

#include <string>

const std::string& foo(const std::string& s = std::string(""))
{
return s;
}

int main()
{
const std::string& s1 = foo();
std::string s2 = foo();

const std::string& s3 = foo("s");
std::string s4 = foo("s");
}

最佳答案

在您的代码中,s1s3 都是悬空引用。 s2s4 没问题。

在第一次调用中,将从默认参数创建的临时空 std::string 对象将在包含调用的表达式的上下文中创建。因此,它会在 s1 定义结束时消亡,从而使 s1 悬空。

在第二次调用中,临时 std::string 对象用于初始化 s2,然后它就消亡了。

在第三次调用中,字符串文字 "s" 用于创建临时 std::string 对象,并且该对象也会在定义结束时消失s3,让 s3 悬空。

在第四次调用中,使用值为 "s" 的临时 std::string 对象来初始化 s4,然后它就消亡了.

参见 C++17 [class.temporary]/6.1

A temporary object bound to a reference parameter in a function call (8.2.2) persists until the completion of the full-expression containing the call.

关于c++ - 可以通过 const 引用返回默认参数的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58663563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com