我有一个函数get
,该函数返回对对象的引用。该函数由另一个函数调用,该函数get2
转发此引用。在中get2
,的结果get
被认为是临时的,这是正确的。但是我可以保证该引用后面的数据不是临时的。
下面的代码重现了该问题:
char * buffer; // for raw binary data, will be allocated somewhere
const char& getRaw(int idx){
return buffer[idx];
}
const int& getInt(int idx){
return getRaw(idx);
}
在这种情况下我该怎么办?(与此同时,我什至可以发布一个解决方案,但只要它搁置,我就无法回答。)
对于经验丰富的C ++程序员,问题应该非常明显:我在getInt中将char&隐式转换为int&。因此,编译器将创建一个临时int并返回对其的引用,而不仅仅是返回char&并将其重新解释为int&。
重新解释演员表有助于:
char * buffer; // for raw binary data, will be allocated somewhere
const char& getRaw(int idx){
return buffer[idx];
}
const int& getInt(int idx){
return reinterpret_cast<const int&>(getRaw(idx));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句