简体   繁体   中英

Performance hit of static_cast pointer types?

static_cast 10,000项指针类型需要多少?

Nitpicker's corner

Other answers pointed out that the cost is zero for pointers; this is correct as far as class hierarchies with single inheritance are involved, but when dealing with multiple inheritance there may be a (very small) cost.

In single-inheritance classes the memory layout of objects is typically arranged so that a pointer to a derived class can be used as a pointer to base class with no adjustments - this is normally accomplished by putting the "parent part" of the object at the front, so that a pointer to Derived is actually also a valid pointer to Base.

But in multiple-inheritance scenarios, you cannot put all the base classes in front of the object; for this reason, when casting a Derived * to Base1 * or to Base2 * , a pointer adjustment may be needed. This typically results in a fixed-size increment to the pointer when doing various operations that involve a pointer to one of the base classes.

Of course, this is completely negligible (it amounts to a single really fast assembly instruction at most), but nonetheless, in this scenario there is a very very slight cost in cast. Notice though that it's not specific to static_cast , it's there whenever you need to treat your Derived * as a Base2 * (including when you simply call Base2 * methods, since also the this pointer needs to be adjusted).

Additional reading: http://www.codeproject.com/Articles/12935/What-static_cast-is-actually-doing

Nothing, it's done at compile time, for pointers. But it's not zero cost for an actual object where work has to be done to convert between types. When you static_cast a pointer all that's really being done is you look at the address in a different way. The casting of an actual object can involve the creation of a temporary and thus has runtime cost of the conversion operator used to create it.

casting should take 0 time, no matter how many times*

*there is a noted exception of pointers in multiple-inheritance scenarios where pointer manipulation must occur, but for cases of single inheritance that static_cast is mearly allowing the code to derefference the pointer in a different way:

take for example:

foo(void *x)
{
    int * j=static_cast<int *>(x);  // costs the same as void *x2=x;
    // the cast above does nothing except allow the copy of the pointer value to j and allow the line below to work
    int k = *j;    // this would not be allowed directly from x without the static_cast
}

had x been multiply inherited instead and cast to a base then the cast would move the pointer to the correct start of base. And not been 0 cost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM