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