Skip to content

Commit c226e3e

Browse files
committed
static_cast vs. reinterpret_cast
1 parent 3b31788 commit c226e3e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

_posts/2023-10-20-C++-Common-Errors-And-Solutions.markdown

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,3 +454,33 @@ In this way, there is no such symbol of the function GraphViewerRef::IsConstantI
454454
leca@host [ ~/code/plugin_pure_virtual ]$ readelf -s --wide libcustom_ep.so | grep -i 'IsConstantInitializer'
455455
leca@host [ ~/code/plugin_pure_virtual ]$
456456
```
457+
458+
# 6. static_cast vs. reinterpret_cast
459+
460+
reinterpret_cast can only perform pointer-to-pointer conversions and reference-to-reference conversions (plus pointer-to-integer and integer-to-pointer conversions). So the following case, there will be an build error:
461+
462+
```cpp
463+
float f = 3;
464+
int i = reinterpret_cast<int>(f); // build error! You can use static_cast instead
465+
```
466+
467+
For the opaque pointer case you can only use reinterpret_cast where you want to cast a pointer to an unimplemented class:
468+
469+
```cpp
470+
struct StructNoImplementaion;
471+
472+
struct StructWithImplementation {
473+
StructWithImplementation(int m) : member1(m) {}
474+
int member1;
475+
};
476+
477+
int main()
478+
{
479+
StructWithImplementation s(3);
480+
// no error
481+
StructNoImplementaion* p = reinterpret_cast<StructNoImplementaion*>(&s);
482+
483+
// error: cannot convert from 'StructWithImplemetation' to 'StructNoImplementation'
484+
//StructNoImplementaion* p = static_cast<StructNoImplementaion*>(&s);
485+
}
486+
```

0 commit comments

Comments
 (0)