4 ms·
Interesting Behaviors of C++ Casts
- SamReidHughes 5y agoAnd now I notice that all my uses of static_cast are either with reference or pointer types or for primitive type conversions, but never in a manner that invokes a class's copy constructor. I didn't realize that C-style casting would behave like static_cast, doing pointer offsets and null checks, if that was available. I had believed it was always reinterpret_cast for pointers.
- steerablesafe 5y agoC-style cast also has a weird "super power" when it tries the `static_cast`: it will happily cast to a pointer of private base (with all the offset adjustments), while normal `static_cast` would fail.
- steerablesafe 5y agoI think the "Static casts can call several conversion constructors" section is misleading. In fact, it has nothing to do with static_cast, it's just you can chain conversions, if you write out some of the conversions explicitly. `BarFoo barfoo = FooBar(foo);` works all the same.
- MauranKilom 5y ago> Static casts can call several conversion constructors Feel free to play with it some more: https://godbolt.org/z/7fGnj6db1 https://godbolt.org/z/7fGnj6db1 It consists of two user-defined conversions in the argument and one user-defined conversion (i.e. converting constructor) in the initialization. The reason for that is: https://timsong-cpp.github.io/cppwp/n4659/over.match.conv#1.1 https://timsong-cpp.github.io/cppwp/n4659/over.match.conv#1.... Hence, the following can actually do four conversion: Foo foo; Bar4 barfoo{static_cast<Bar2>(foo)};
- dataflow 5y agoThere's one type for which I will almost always use a C-style cast rather than a C++ cast: void foo(int unused) { (void)unused; } or alternatively, in situations like: template<class T> typename std::enable_if<((void)sizeof(T), true)>::type foo(T &&); Edit: Also note that static_cast isn't quite like a function call, because it does something a function call does not, which is to extend the lifetime of the temporary it's operating on. To see the difference, try replacing static_cast here with static_cast_: #include <stdio.h> struct B { }; struct S : B { ~S() { printf("~S(): %p\n", static_cast<void *>(this)); } S() { printf("S(): %p\n", static_cast<void *>(this)); } S(const S &) { printf("S(const S &): %p\n", static_cast<void *>(this)); } S &operator =(const S &) { printf("S &operator =(const S &): %p\n", static_cast<void *>(this)); return *this; } }; static S foo() { return S(); } template<class To, class From> To static_cast_(const From &v) { return static_cast<To>(v); } int main(int argc, char *argv[]) { (void)argc; (void)argv; const B &b = static_cast<const B &>(foo()); printf("Middle: %p\n", static_cast<const void *>(&b)); (void)b; } The compiler "sees through" the cast to extend the lifetime of the object returned by foo(), which produces different output.
- steerablesafe 5y agoDo you `enable_if` on completeness of a type? I would recommend against it, it's prone to ODR violations.
- dataflow 5y agoNot in functions I believe (that was just for illustration), but in other occasions, yes, it's happened - sometimes it's necessary with template metaprogramming.
- steerablesafe 5y agoI'm curious about a valid use case there. If you have a minimal example, or a link to some public code, I would love to see it. There is a reason to be cautious there, the standard library also tends to static_assert on completeness instead of trying to be SFINAE-friendly.
- gpderetta 5y agoI always use the appropriate *_cast<> when converting pointers; Unsafe pointer casts are rare and it is good that they stand up. I do like the C cast syntax for scalar casts though as they are often used to silence warnings for conversions that would happen anyway. I wish there was a variant of -Wold-style-cast just for pointer types.
- steerablesafe 5y ago> I wish there was a variant of -Wold-style-cast just for pointer types. And for reference types, pointer to members, pointer to/from integral and dependent types (which could become any of the above upon instantiation). But I do agree, with some concrete types it can be convenient.
- im3w1l 5y ago> Objectively, there are absolutely no upsides to using a C-style cast. It's shorter. I'm pretty sure that's the main reason people use it.
- wheybags 5y ago100%, the c++ style casts are huge and unwieldy to type. Also, for casting between integer types, you can actually reverse the bracketing so it looks like a nice clean conversion function. Eg, these two expressions are the same: int32_t(x); (int32_t)x;
- olvy0 5y agoConversely, once in about 6 months people call me to debug a "strange crash" and it turns out it's because they used a c-style cast, when using static_cast would have resulted in a clear compiler error. To be clear, this is in a code written by people who are not exactly professional programmers, but rather a mix between support/integration personnel. They are responsible however for some rather basic glue code which I pull from them. They are an interesting mix between real old timers who only know C well, and young people who only learned about Java and Python, with only a minimal background in C. Both of groups sort of "feel their way" around C++ code. Luckily I catch most of their mistakes during code reviews. I try to educate them every time that they should use static_cast. Yes, I say, it's ugly and hard to type, that's true. But you will get an error during compilation, and you won't crash, and I won't have to go to your computer to debug your crash.
- 29athrowaway 5y agoI don't know if this helps, but I often delete the constructors I don't need, and also make them explicit.