传递常量引用...它是否像最重要的常量一样工作?
Passing constant reference... does it work like most important const?
这是一个已知的特殊情况,如果将常量引用分配为常量引用,则常量引用不会在 return 值中丢失:
int MyFunction()
{
int x = 5;
return x;
}
int main()
{
const int& y = MyFunction();
std::cout << "This is valid: " << std::endl;
return 0;
}
现在如果我有如下两个函数:
int MyFunction()
{
int x = 5;
return x;
}
void MyOtherFunction(const int& val)
{
std::cout << val << std::endl;
}
int main()
{
MyOtherFunction(MyFunction());
}
这项工作符合标准吗?传递 const 引用有什么限制?
这也很好:标准要求匿名临时 (MyFunction()
) 可以绑定到 const 引用。
(它不能绑定到非常量引用;一些编译器在这方面失效了)。
是。
[C++14: 12.2/5]:
[..] 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. [..]
有效。 .
Reference只是你的变量的别名,它代表变量存储的地址位置。
const 引用意味着你不能在你的函数中修改你的 const 参数。
在你的情况下,
MyOtherFunction(MyFunction());
这里是 MyFunctions returns 一个 int,它存储为匿名变量,其生命周期取决于该表达式。
这是一个已知的特殊情况,如果将常量引用分配为常量引用,则常量引用不会在 return 值中丢失:
int MyFunction()
{
int x = 5;
return x;
}
int main()
{
const int& y = MyFunction();
std::cout << "This is valid: " << std::endl;
return 0;
}
现在如果我有如下两个函数:
int MyFunction()
{
int x = 5;
return x;
}
void MyOtherFunction(const int& val)
{
std::cout << val << std::endl;
}
int main()
{
MyOtherFunction(MyFunction());
}
这项工作符合标准吗?传递 const 引用有什么限制?
这也很好:标准要求匿名临时 (MyFunction()
) 可以绑定到 const 引用。
(它不能绑定到非常量引用;一些编译器在这方面失效了)。
是。
[C++14: 12.2/5]:
[..] 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. [..]
有效。 . Reference只是你的变量的别名,它代表变量存储的地址位置。
const 引用意味着你不能在你的函数中修改你的 const 参数。
在你的情况下, MyOtherFunction(MyFunction());
这里是 MyFunctions returns 一个 int,它存储为匿名变量,其生命周期取决于该表达式。