据Resharper说,这里的c ++是无效的:
class IData{
IData();
virtual doStuff() = 0;
}
class MyData: public IData{
MyData(MyData&& mdrv);
doStuff() override{/*....*/};
}
class DataUser(){
DataUser(IData& d){ //all explicits are ommitted for brevity, don't call me out on that please :)
d.doStuff();
}
}
int main(){
DataUser d(MyData()); //it complains here: Binding Rvalue Reference to lvalue Reference is a non standard MSVC extension
}
我不能让IData& const ,因为doStuff做了东西(呃!)
我做的是:
class DataUser(){
DataUser(IData& d){
d.doStuff();
}
DataUser(IData&& d): DataUser(d){ //added this, no complains anywhere
}
}
现在我的问题是:
答案 0 :(得分:0)
由于@Incomputable提供了惊人的帮助,我能够解决这个问题。
归结为以下事实:
可以找到其他资源(由@Incomputable再次提供)
Here (especially the paragraph entitled Rvalue references is very good)和https://pbs.twimg.com/profile_images/450103729383956480/Tiys3m4x.jpeg
这就是为什么
class DataUser(){
DataUser(IData& d){
d.doStuff();
}
}
int main(){
DataUser d(MyData()); //lvalue ref is initalized with rvalue, Rvalue goes out of scope --> UB
}
但
class DataUser(){
DataUser(IData& d){
d.doStuff();
}
DataUser(IData&& d): DataUser(d){ //the rvalues lifetime is extended until the constructor exits and d goes out of scope
}
}
int main(){
DataUser d(MyData()); //this works like a charm and is perfectly legal
}