什么时候 int i = 5;
int j = i;
Run Code Online (Sandbox Code Playgroud)
i在评估结果时,此表达式中的rvalue 是否为常量?
我问这个问题,因为在我的复制构造函数中,它的参数需要一个 const
Dav*_*eas 15
围绕左值/右值术语存在一个常见的误解.它们不是指变量,而是指表达式.表达式可以产生左值或右值,并且可以是const或非const.
特别是,在您的代码i中,定义右侧的表达式int j = i;是左值表达式,而不是右值.为了赋值,有一个左值转换的左值,然后分配给新声明的变量.
连接是一个正交概念 - 在大多数情况下 - 与你是否可以改变你正在处理的对象有关.
int f();
int& g();
const int& h();
const int k();
int main() {
f(); // non-const rvalue expression
g(); // non-const lvalue expression
h(); // const lvalue expression
k(); // const rvalue expression
f() = 5; // error, cannot assign to an rvalue
g() = 5; // correct, can modify a non-const lvalue
h() = 5; // error, cannot modify a constant lvalue
}
Run Code Online (Sandbox Code Playgroud)
其他示例需要使用用户定义的类型:
struct test {
void foo() { x = 5; }
void bar() const;
int x;
};
test f();
const test g();
int main() {
f().foo(); // f() is a non-const rvalue,
// but you can call a method on the resulting object
g().foo(); // g() is a const rvalue,
// you cannot call a mutating member function
g().bar(); // but you can call a const member function
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1150 次 |
| 最近记录: |