Skip to content

Comment on Why C++ Is Terrifying

Comments

Since the HN username matches the twitter name, I'll bite: Is it the case that a raw function pointer is always trivially copyable?

I'm not super familiar with C++'s memory model, especially since they have deprecated the notion of POD and replaced it with trivially constructable.

My rudimentary thought process is that you can't just "move" raw functions because there is probably some assumptions made that a C++ function's call-site isn't going to move around if it isn't owned by an object. Otherwise, the runtime would have to deduce the location of the function call every time.

Well, on second thought, is there any reason why an int function ptr should be any different from an int ptr?

Asking as someone who has been writing C++ on-and-off for a few years for games, school, etc. but never professionally.

I didn't fully catch your reasoning regarding the call-site of functions, but if your specifically talking about function pointers, then they are not closures so call-site doesn't matter.

Well, on second thought, is there any reason why an int function ptr should be any different from an int ptr?

I don't know any other example, but in Itanium, a function pointer is not just an address but an (address+address) pair where the second address is a sort of a base pointer for data segment:

https://stackoverflow.com/a/18908021

I don't think this is true except maybe on ancient architectures. function ptrs are usually just addresses (64 bits on most modern computers). virtual member function ptrs can have an extra bit of info to resolve the this ptr at runtime.

so usually (but not always), sizeof(int ptr) == sizeof(func ptr)

The answer is yes. And you can verify this by

checking std::is_trivially_copyable<FnPtrType>::value

using FnPtrType = int (*)(int) // for example

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.