分配易失性右值

Assigning a volatile rvalue

本文关键字:易失性 分配      更新时间:2023-10-16

我不明白为什么下面的代码无法编译:

#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.3

20120306 (Red Hat 4.6.3-2)

根据 [dcl.init.ref]/5,对于要通过绑定到 rvalue 来初始化的引用(即 Test::operator=() 的参数),该引用必须是constvolatile的左值引用或右值引用:

— 否则,引用应是非易失性常量类型的左值引用(即 cv1 应为 const ),或者引用应为右值引用。

b = c;有效,因为您将引用(Test::operator=() 的参数)绑定到左值。