我希望了解为什么const volatile引用不能绑定到右值引用?禁止这种转换的合理原因是什么?
在下面的代码中,我注释掉了无法编译的行:
int main(){
int i=1;
//const volatile int& cvi2=std::move(i); -> ERROR: why?
const volatile int i2=0;
//const volatile int& cvi3=std::move(i2);// -> ERROR: why?
}
这里有一个更现实的场景,因类似原因而无法编译:
#include<iostream>
template<class T> void g(const T& b){
//do usefull things
}
template<class T,class F> void f(T& a,F a_func){
//do usefull things with a
a_func(std::move(a));
}
int main(){
int i=0;
volatile int vi=1;
f(i,g<int>); //OK no error;
f(vi,g<volatile int>);//ERROR: can not convert volatile int to
//const volatile int &
}
在这段代码中,我本来期望
g<volatile int>(const volatile&)
可以接受任何参数。下面是一个更具体的示例:
#include <vector>
using usefull_type=int;
void set_communication_channel_to(volatile usefull_type* g,size_t n);
int main(){
auto vect=
std::vector<volatile usefull_type>(10,usefull_type{42});//->ERROR no known conversion
// from int to const volatile int &
set_communication_channel_to(vect.data(),vect.size());
//...
//...
}
这个限制肯定有很好的理由,不是吗?
const volatile
这个是什么意思? - πάντα ῥεῖvolatile
表示该值可能会被外部原因(如其他线程)改变,这与只能将常量引用绑定到临时对象的规则相矛盾。 - Emerald Weapon