相关疑难解决方法(0)

const引用类成员是否延长了临时生命?

为什么这样:

#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)

给出输出:

答案是:

代替:

答案是:四

c++ temporary const-reference ctor-initializer

157
推荐指数
3
解决办法
4万
查看次数

是否可以将纯右值显式转换为 const 引用以避免三元运算符中的额外复制?

假设我们有一些不可复制和不可移动的类型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)

这不会编译,因为fooFoo{ 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)

c++ conditional-operator prvalue

6
推荐指数
0
解决办法
152
查看次数