The cost of a link to a static_cast link and a pointer to a static_cast pointer

Does the link to the static_cast link have the same runtime cost as a pointer to a static_cast pointer?

eg.

class B;
class A: public class B;

A obj;
A& ref = obj;
A* ptr = &obj;

// 1
static_cast<B&>(ref);
// 2
static_cast<B*>(ptr);
+4
source share
2 answers

No, they do not always have the same value. When optimization is enabled, they always have the same or almost the same cost.

If you create or reduce an inheritance hierarchy in which either

  • multiple inheritance is involved or
  • a polymorphic class inherits from a non-polymorphic class,

a static_cast , static_cast .

, , , static_cast : .

, static_cast , , null, . , , , , .

, static_cast . this , this .

, , static_cast.

. , . .


:

struct A { int a; };
struct B { int b; };
struct C : A, B { int c; };

B* cast(C* ptr) { return ptr; }
B& cast(C& ref) { return ref; }

: ( GCC -O2)

cast(C*):
        leaq    4(%rdi), %rax
        testq   %rdi, %rdi
        movl    $0, %edx
        cmove   %rdx, %rax
        ret
cast(C&):
        leaq    4(%rdi), %rax
        ret
+3

- , . static_cast ( MSV++) - , .

+1

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


All Articles