为什么这样:
#include <string>
#include <iostream>
using namespace std;
class Sandbox
{
public:
Sandbox(const string& n) : member(n) {}
const string& member;
};
int main()
{
Sandbox sandbox(string("four"));
cout << "The answer is: " << sandbox.member << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
给出输出:
答案是:
代替:
答案是:四
假设我们有一些不可复制和不可移动的类型Foo,以及一个函数
int f(const Foo& foo) {
... // somehow compute the result depending on the value of foo.
}
Run Code Online (Sandbox Code Playgroud)
现在假设我们想像这样调用这个函数:
const Foo foo1{ 42 };
bool condition = getCondition();
int result = f(condition ? foo : Foo{ 150 });
Run Code Online (Sandbox Code Playgroud)
这不会编译,因为foo和Foo{ 150 }属于不同的值类别,因此,根据定义,三元运算符将返回类型的纯右值Foo- 这意味着foo1需要复制 if condition == true,因此这会导致编译错误。
然而,C++ 保证临时对象在表达式结束之前保持有效,因此我们可以这样写:
const Foo foo1{ 42 };
bool condition = getCondition();
int result = f(condition ? foo1 : static_cast<const Foo&>(Foo{ 150 }); …Run Code Online (Sandbox Code Playgroud)