We were taught about static_cast in the C++ course, but I completely forgot what it does

@vaporeon_ to oversimplify a bit it's like a c-style cast that has a lot more restrictions,and is checked by the compiler, to protect the programmer from making silly mistakes

@wallhackio What kind of silly mistake? In my mental model, a cast is a way to tell the compiler "I know what I'm doing, don't complain and just consider this type as this other type", and now you're telling me there's a version of that with extra checks?

@wallhackio Somewhat relatedly, can you tell me why the C++ compiler is complaining about this very normal code?

#include <stdlib.h>
int main() {
char *str = malloc(123);
}
$ g++ test.cpp
test.cpp: In function 'int main()':
test.cpp:3:21: error: invalid conversion from 'void*' to 'char*' [-fpermissive]
3 | char *str = malloc(123);
| ~~~~~~^~~~~
| |
| void*

Sure, a void* is not a char*, but the void* is intended to be casted to some other type because you can't dereference a void*, and in C this code just works... Why did they choose to make my life harder?!

@vaporeon_ it was a very deliberate design choice when C++ was made in the 80s to not allow implicit void* conversions. It's one of the few very deliberate situations C++ fails to be a superset of C. You have to explicitly cast a void pointer to the exact type you want it to be

You can disagree with this choice but it was a choice made from basically the very beginning

@wallhackio Am I supposed to not be using malloc() in C++ and be using something else instead?

Follow

@vaporeon_ @wallhackio it’s a very abnormal thing to do, to my understanding

@vaporeon_ @wallhackio use classes? (they auto-destruct when they go out of scope.) if you need to hold a pointer to something use C++ various “smart” pointer wrappers? i feel like caleb would have a better answer though

@vaporeon_ @aescling there's almost always some sort of standard library container class for anything you'd use malloc for. I'd much sooner default to std::string in your situation

If the container doesn't exist then you can use the new keyword. I don't know of a situation you would use malloc other than to interface with C libraries or legacy C++ code

Sign in to participate in the conversation
📟🐱 GlitchCat

A small, community‐oriented Mastodon‐compatible Fediverse (GlitchSoc) instance managed as a joint venture between the cat and KIBI families.