分配易失性右值

时间:2015-01-20 14:46:46

标签: c++ 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,当我遇到这种情况时,我正在尝试使用volatile来禁用它。编译:

  

-fno-的Elid-构造

没有任何区别。

对此有何解释? 测试:

  

g ++(GCC)4.6.3 20120306(Red Hat 4.6.3-2)

1 个答案:

答案 0 :(得分:4)

Per [dcl.init.ref] / 5,对于要通过绑定到右值来初始化的引用(即Test::operator=()的参数),引用必须是{ {1}}非const左值参考或右值参考:

  

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

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