Does C style casting adds assembly (code) or is it only for the compiler to understand the situation?

我的未来我决定 提交于 2019-12-11 06:02:45

问题


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:

  1. Expanding casts on signed integers: The cast inserts a sign extension instruction to preserve the value of negative values.

  2. 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.

  3. 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 a SecondBase* 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!