将右值分配给右值 [英] Assigning rvalue to rvalue
问题描述
请问为什么下面的代码可以编译不出错?
struct Test {整数;};int main() {(测试){.num = 10} = (测试){.num = 20};返回0;}
(Test){.num = 10}
和 (Test){.num = 20}
是右值,这是不可能将一个右值分配给另一个右值.cpp 如何认为该语句有效?
PS:代码使用C++11标准编译
这就是默认情况下在 C++ 中指定特殊成员函数的方式.例如Test
有一个合成的特殊成员函数:
测试&运算符=(测试常量&)=默认值;//如果你写出来
可以在左值和右值上调用.
如果你想禁止对右值赋值,你必须自定义类的行为:
struct 测试 {整数;测试&operator=(Test const &) &= 默认值;//左值:好的测试&operator=(Test const &) &&= 删除;//右值:错误};
这是 C++20 中的 演示,就像您示例中的代码一样,但相同原则适用于 c++11.
请注意,对于内置类型,行为更明智,因此您不能这样做:
42 = 5;3 + 3 = 6;
而且没有办法让它编译.</p>
Can I ask why the code below can be compiled without any error?
struct Test {
int num;
};
int main() {
(Test){.num = 10} = (Test){.num = 20};
return 0;
}
(Test){.num = 10}
and (Test){.num = 20}
are rvalue, this is impossible that a rvalue can be assigned to another rvalue. How cpp considers the statement is valid?
PS: the code is compiled using C++11 standard
This is just how the the special member functions are specified in c++ by default. e.g. Test
has a synthesized special member function:
Test& operator=(Test const &) = default; // if you write it out
which can be called on both lvalues and rvalues.
If you want to disallow assignments to rvalues, you have to customize the behavior of the class:
struct Test {
int num;
Test& operator=(Test const &) & = default; // lvalues: ok
Test& operator=(Test const &) && = delete; // rvalues: error
};
Here's a demo in c++20, like the code in your example, but the same principle applies in c++11.
Note that for in-built types, the behavior is more sensible, so you can't do this:
42 = 5;
3 + 3 = 6;
and there's no way to let that compile.
这篇关于将右值分配给右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!