Hacker News new | ask | show | jobs
by voidUpdate 2 days ago
> "An interesting question you may ask in C++ is: “How would you declare a function that takes a blob of memory as input?”"

> "Now, suppose that you want to pass to this function a custom structure, like this:"

You would create another function that actually works based off that structure, rather than using your first function which operates on a set of bytes in memory. That way it's readable, like they want, and type-safe

1 comments

I find this to be a snarky non-answer. You really think everyone should write their own memcpy for every POD type they want to memcpy?
There's no need: there's std::copy already.

Or maybe the idea was to create a typesafe template wrapper around the generic function which is also very common and really nice. No need to create one wrapper per type, a single template should work.

And how was std:copy implemented?

Your answer is valid only for a programming language which assumes that the standard library is implemented in another language.

C/C++ are supposed to be languages in which any program can be written, unlike languages like Java or Python.

Yes, C++ has those parts. You can use them to write something like std::copy. But use them, once, to write std::copy, and get that one implementation right (or have the library writers do it for you), and then use std::copy everywhere, rather than using void* everywhere. This makes your program much more type safe and less buggy, while still letting you write the parts where you really need to use the down-and-dirty stuff.
You cannot implement modern C++ in pure C++ nowadays, as the standard library requires compiler intrisics, just like a language like Java.
In addition to what mfrost said, there's also no need because C++ assignment is member-by-member copy unless otherwise specifically implemented for the type. If you have a POD, then that's what you get with assignment; there's no need to call memcpy at all.

(The difference is that memcpy will copy padding bytes, and the assignment operator may not. But if you depend on the values of the padding bytes, you have major problems...)