C++ Build warning in GCC ARM but not MS x86
I use the Airplay SDK which is a platform for building C++ apps for smartphones. It als开发者_运维知识库o has a x86 simulator which uses MS Visual C++ IDE + compiler.
Now, I have this class :
namespace Fair {
class Bitmap : public Sprite {
public:
const CIw2DImage* const& getBitmapData() { return bitmapData; }; // warning: returning reference to temporary
private:
CIw2DImage* bitmapData;
};
}
I get the above warning if I build with GCC (ARM) Debug. I don't get a warning with (x86) Debug.
I asked elsewhere and I got this reply :
Because `const CIw2DImage* const' is a const pointer to const CIw2DImage, and Bitmap::bitmapData is a pointer to non-const CIw2DImage compiler automatically casts pointer to non-const to const, so here's a temporary. The following code might be generated by a "typical" compiler:
const CIw2DImage* const& getBitmapData() { const CIw2DImage* const tmp = bitmapData; return tmp; }
Probably (x86) compiler doesn't detect this problem.
You might want to remove reference symbol (&) from the prototype (why do you want use a reference in this case?)
If a compiler does that, then it's totally wrong practice..? Making the value returned more "strict" is simply at compiler-level, to prevent "abuse". (x86) doesn't detect because it doesn't "cause" the problem in the 1st case..?
I return a reference to a pointer for the sole reason to "save" 32 bits of memory, i.e. use the same block of memory as the bitmapData pointer but within a different context.
Any comments please?
The compiler is quite correct to do that. A reference must refer to an object of the correct type; here you have an object of type CIw2DImage*
, and you need a reference to a different type, const CIw2DImage*
. The only way to do this is to create a temporary of the correct type (which is possible here, since const T*
can be implicitly converted to T*
), and return a reference to that.
Unfortunately, that results in a reference to a temporary object in the scope of the function, which is no longer valid once the function returns.
The simplest solution is to return the pointer by value; this will be more efficient (as it avoids an unnecessary level of indirection), as well as avoiding this problem.
You won't save any memory at all returning a reference, it's just a pointer internally. In addition, const occurs completely at compile-time, there's no reason for any temporary to be produced- and even if it was, a const reference to it would be valid.
That code looks terrible to me personally but it's not undefined in any way.
精彩评论