const引用默认值 [英] const reference 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());
错误foo2():'std :: string& s'有类型'std :: string {aka std :: basic_string< char>}'
我理解编译器的观点,不会得到这不适用于 foo1()
以及。
I understand the compiler's point, but I don't get how this does not apply to foo1()
as well.
推荐答案
你不能像foo2那样对一个临时对象进行非const引用。
You can't take a non-const reference to a temporary like foo2 does.
注意,这不是默认的参数。对于函数变量,您会遇到相同的错误: http://ideone.com/g7Tf7L
Notice that this isn't specifically default parameters. You get the same error for function variables: 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,引自我的C ++ 11草案n3337的副本):
When you take a const reference to a temporary, the lifetime of the temporary is extended to the lifetime of the reference (§12.2, quoted from my copy of C++11 draft 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:
- 在构造函数的ctor-initializer(12.6.2)中临时绑定到引用成员,直到构造函数退出。
- 在函数调用(5.2.2)中,引用参数的临时绑定将持续到包含调用的完整表达式完成为止。
- 在函数return语句(6.6.3)中绑定到返回值的临时的生命周期不会被延长;临时将在return语句中的full-expression结尾处销毁。
- 暂时绑定到新初始化程序(5.3.4)中的引用,直到完成包含新初始化程序的完整表达式。
- 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.
这篇关于const引用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!