C++了解默认参数中的引用

C++ understand reference in default parameter

本文关键字:引用 参数 了解 默认 C++      更新时间:2023-10-16

我对C++默认参数中的引用有疑问。

示例 : SWindows(const std::string&, int, const std::string& flag = "UDP");

我不明白为什么这段代码编译(IDE Visual studio 2012)。对我来说,引用它是一个对象别名。所以我们不能声明这条线。应该"标志"已经存在。

所以这是编译器优化还是误解?

const lvalue 可以绑定到临时对象。就这样。因此,该代码是合法且格式良好的。

只要该临时对象的生存期存在flag就会延长。不用说,你不能将临时对象绑定到非常量左值引用。

理解代码

SWindows(const std::string&, int, const std::string& flag = "UDP");

您应该将其分为两部分。

SWindows(const std::string&, int, const std::string& flag );
SWindows( SomeString, SomeInt, "UDP" );

由于"UDP"不是 std::string 类型,因此通过调用接受字符串文本作为其第一个参数的构造函数,它隐式转换为 std::string 类型的对象。所以最后一句话相当于

SWindows( SomeString, SomeInt, std::string( "UDP" ) );

表达式 std::string( "UDP) 的结果是一个临时对象,您可以将其绑定到 const 引用。因此,const 引用是该临时对象的别名,

你可以想象这样一种方式,在函数的主体内部有定义

const std::string &flag = std::string( "UDP" );

您可以使用常量引用来做到这一点。您还可以将右值与常量引用一起使用,例如:

void SomeFunction(SomeObject const& s)
 { ... };

然后你可以打电话

SomeFunction(SomeObject());

你可以这样做,因为通过说它是一个常量引用,你告诉你不会修改引用的变量。如果不是const&你将无法做到这一点。