问题
Class A
{
public:
A *GetA(void) { return a; }
protected:
A *a;
};
Class B : public A
{
public:
B *GetB(void) { return (B*)a; }
};
In class A I assume that the compiler (ideally) will optimize and inline the getter to no different code than accessing the variable directly ?
In class B the variable is cast to B. Is this purely for the compiler or does this also involve code ? Will the assembly instructions be the same for the function in B ?
回答1:
Most casts do not insert any assembler instructions, however, there are exceptions:
Expanding casts on signed integers: The cast inserts a sign extension instruction to preserve the value of negative values.
Casts to and from floating point types: These casts perform a full conversion, they do not reinterprete the bits. Consequently, the computer has to do something.
Pointer casts with multiple inheritance. While the first base is always the first member in an object, the second base can't be. So, casting a
Derived*
to aSecondBase*
will adjust the pointer, adding an addition instruction to the code.
回答2:
For any sensible compiler, in case of single inheritance the change of pointer type will just affect the compiler metadata - the code will be the same -, but keep in mind that in case of multiple inheritance casting to one base class or the other will most probably provide a different value for the pointer.
This series goes into the gory details of an implementation, you may find it interesting.
回答3:
It depends on the operation being done. The example you give is not necessarily valid; if a
points to an instance of class A
then casting a
to B*
invokes undefined behaviour. This is what dynamic_cast<>
is for. Supposing that the operation is valid, then there should be no run-time overhead involved because of the cast.
In another case, there is run-time behaviour involved:
int a = 5;
double b = (double)a / 2;
Without the cast, this would invoke integer division and implicitly cast the result to double
. With the explicit cast, both a
and 2
are cast to double, floating-point division is used and the result is stored in b
.
来源:https://stackoverflow.com/questions/26858683/does-c-style-casting-adds-assembly-code-or-is-it-only-for-the-compiler-to-unde