Do polymorphic C-style castings have overhead?

  • Does any pointer to an instance of the dervived class for the base instance class have any overhead at runtime in C ++, or is it allowed at compile time?

  • If this is true, what exactly should be calculated in the casting operation?

Example:

class Foo; class Bar : public Foo; Bar* y = new Bar; Foo* x = (Foo*) y; 

(I know that I should use C ++ style and that the answer is probably the same for them)

+4
source share
4 answers
 Foo* x = (Foo*) y; 

You do not need to throw Bar* at Foo* . Selection from Derived to Base is implicit:

 Foo* x = y ; // is enough! 

As for polymorphic casting, the C-style cast is not equivalent to dynamic_cast . C ++ dynamic_cast is a completely new feature added to the language and not having a C-style matching.

Does a pointer to an instance of a class caused by a virus infer the base class has time overhead in C ++, or is it allowed at compile time?

Transmission from a derivative to the base is allowed at compile time if you do what I did above. Thus, it has no overhead at runtime.

+5
source

Yes, although this is insignificant.

In this case, the C-style static_cast interpreted as static_cast , which may lead to adjustment of the pointer.

 struct Base {}; struct Derived: Base { virtual ~Derived(); } // note: introduced a virtual method int main() { Derived derived; Base* b = &derived; Derived* d = (Derived*) b; void* pb = b; void* pd = d; printf("%p %p", pb, pd); return 0; } 

This overhead occurs when the underlying subobject does not align to the same address as the derived object, which occurs when:

  • introduction of the first virtual method
  • using multiple inheritance

Of course, adjusting the pointer is usually considered insignificant, and the compiler should be smart enough to exclude it if it is not needed in any case (setting 0).

Note: this is implementation dependent, not standard

+5
source

C casts have no runtime overhead. The only casting operation that creates ancillary data at runtime is dynamic_cast<>() , because it checks information such as runtime.

+2
source

See the answer to a similar question: regular casting against static cast and dynamic giving

To summarize: when creating a C-style, runtime is not required at runtime because it tries to collect C ++ methods other than dynamic_cast (which imposes a runtime penalty).

+1
source

Source: https://habr.com/ru/post/1340982/


All Articles