gpt4 book ai didi

c++ - const 引用默认值

转载 作者:IT老高 更新时间:2023-10-28 22:18:50 26 4
gpt4 key购买 nike

Possible Duplicate:
how to initialize function arguments that are classes with default value

#include <string>

void foo1(const std::string& s = std::string());

void foo2(std::string& s = std::string());

void foo3(const std::string s = std::string());

void foo4(std::string s = std::string());

error at foo2(): default argument for ‘std::string& s’ has type ‘std::string {aka std::basic_string<char>}’

我理解编译器的意思,但我不明白这不适用于 foo1()也是。

最佳答案

您不能像 foo2 那样对临时对象进行非常量引用。

请注意,这不是专门的默认参数。对于函数变量,您会得到相同的错误:http://ideone.com/g7Tf7L

#include <string>
using std::string;

#include <iostream>
using std::cout; using std::endl;

int main()
{
string s1 = string("s1"); // OK, copy it
const string& s2 = string("s2"); // OK, const reference to it
string& s3 = string("s3"); // ERROR! non-const reference not allowed!

cout
<< s1 << ", "
<< s2 << ", "
<< s3 << endl;
return 0;
}

当您对临时对象进行 const 引用时,临时对象的生命周期会延长到引用的生命周期(第 12.2 节,引 self 的 C++11 草案 n3337 拷贝):

There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression.

...

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

  • A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
  • A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
  • The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.
  • A temporary bound to a reference in a new-initializer (5.3.4) persists until the completion of the full-expression containing the new-initializer.

关于c++ - const 引用默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14612933/

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