最近遇到的問題,很容易疏忽的問題
有些function parameter只收 int& (call by refernce)
像是 void ExternalDisplay::getAttributes(int& width, int& height)
有時候我們在呼叫的fuction裏面,為了貪圖方便想說直接轉
float fbWidth = ctx->dpyAttr[dpy].xres;
float fbHeight = ctx->dpyAttr[dpy].yres;
如果你轉成(int)想要傳,
ctx->mExtDisplay->getAttributes((int)fbWidth, (int)fbHeight); 這樣,會build error
他會說(int)是rvalue,是temporary的值,function傳遞不可以傳遞temporary值,必須是lvalue
轉成int&,雖然這樣就可以compile過,
ctx->mExtDisplay->getAttributes((int&)fbWidth, (int&)fbHeight); 這樣
但請注意這是很危險的,因為這種轉法他會直接直譯,這跟你預期的直會不一樣!!!
他會將float的值直接用int表示
如下function
float fbWidth = ctx->dpyAttr[dpy].xres;
float fbHeight = ctx->dpyAttr[dpy].yres;
ALOGE("CONY fbWidth %.2f,fbHeight %.2f",fbWidth,fbHeight);
ALOGE("CONY fbWidth %d,fbHeight %d",(int&)fbWidth,(int&)fbHeight);
和實際印出來的值
E qdhwcomposer: CONY fbWidth 1920.00,fbHeight 1080.00
E qdhwcomposer: CONY fbWidth 1156579328,fbHeight 1149698048
跟想像的不一樣吧!!!