C++了解默认参数中的引用
C++ understand reference in default parameter
我对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&
你将无法做到这一点。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 具有常量引用参数的函数模板专用化
- C++:常量引用参数
- 字符串引用参数的效率C++
- 通过非常量引用参数修改常量引用参数
- 如何将指针变量作为引用参数传递?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 移动类的成员作为常量引用参数传递
- C++带有适用于左值和右值的引用参数的函数
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 委托构造函数和引用参数
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 如何强制函数仅接受左值引用参数
- 模板引用参数推断失败C++
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 将unique_ptr作为引用参数或常量传递unique_ptr引用