分配易失性右值
Assigning a volatile rvalue
我不明白为什么下面的代码无法编译:
#include <iostream>
class Test {
public:
Test() {
std::cout << "Constructor" << std::endl;
}
Test(const Test&) {
std::cout << "Copy Constructor" << std::endl;
}
Test& operator=(const Test&) {
std::cout << "Assign Op" << std::endl;
return *this;
}
Test& operator=(const volatile Test&) {
std::cout << "Volatile Assign Op" << std::endl;
return *this;
}
};
volatile Test func() {
Test a;
return a;
}
int main() {
Test b;
volatile Test c;
b = c; // this line is correct
b = func(); // this line doesnt compile correct
return 0;
}
该行:
b = c; // this line is correct
而:
b = func(); // this line doesn t compile
编译抱怨:
test.cc: In function ‘int main()’:
test.cc:31:14: error: no match for ‘operator=’ in ‘b = func()()’
test.cc:31:14: note: candidates are:
test.cc:12:11: note: Test& Test::operator=(const Test&)
test.cc:12:11: note: no known conversion for argument 1 from ‘volatile Test’ to ‘const Test&’
test.cc:17:11: note: Test& Test::operator=(const volatile Test&)
test.cc:17:11: note: no known conversion for argument 1 from ‘volatile Test’ to ‘const volatile Test&’
一开始我认为这是由于构造函数 elision,当我遇到这种情况时,我正在尝试如何使用易失性禁用它。编译方式:
-FNO-elide-构造函数
没有任何区别。
对此有什么解释吗?测试方式:
g++ (GCC) 4.6.320120306 (Red Hat 4.6.3-2)
根据 [dcl.init.ref]/5,对于要通过绑定到 rvalue 来初始化的引用(即 Test::operator=()
的参数),该引用必须是const
非volatile
的左值引用或右值引用:
— 否则,引用应是非易失性常量类型的左值引用(即 cv1 应为
const
),或者引用应为右值引用。
行b = c;
有效,因为您将引用(Test::operator=()
的参数)绑定到左值。
相关文章:
- 易失性sig_atomic_t的内存安全性
- C++易失性:保证 32 位访问?
- 避免易失性和非易失性成员函数的代码重复
- 当 2 个线程共享同一物理内核时,具有错误共享的易失性增量在发布中的运行速度比在调试中慢
- 如何访问常量易失性 std::array?
- 为什么在 C++20 中弃用易失性?
- 根据 MSVC,具有易失性成员的结构不再是 POD
- 是否允许编译器优化掉局部易失性变量
- 访问共享内存而不使用易失性、std::atomic、信号量、互斥锁和自旋锁
- 如何避免对无锁程序使用易失性?
- C++:易失性实例中的易失性成员函数 - 将数组分配给指针是无效的转换?
- g++ 6.3,avx 内联函数上的 Kahan 求和用易失性关键字进行序列化
- 是什么让这种易失性打破了结构的指针算法?
- 如果不需要易失性,为什么 std::atomic 方法会提供易失性重载
- *(易失性无符号整数 *) 的含义 0x00 = 0x00;
- 使用易失性 c 字符串和 std::cout
- 易失性结构 = 结构不可能,为什么?
- 如何强制 GCC 以线性方式转换易失性内联程序集语句
- 分配易失性右值
- 为什么不能将易失性文件*分配给文件*?