4 ms·
utf16_output.size() * sizeof(char16_t) Keep on keeping on, c++.
by imron 5y ago
utf16_output.size() * sizeof(char16_t)
Keep on keeping on, c++.
- jstimpfle 5y agowhat's the matter?
- imron 5y agoIt’s 100% correct c++. Used as an example to demonstrate a self-described best of breed library, using all of the latest and greatest features of modern c++ (c++20 features even), and yet you still have to multiply the size of the container by the size of the data type inside the container in order to have correct behaviour. It’s error prone, even for experienced and careful programmers, and despite all the advances of modern c++, this sort of thing permeates through almost every non-trivial c++ project. I didn’t read the library’s documentation so maybe there’s an overloaded output operator that prevents people from needing to do this manually, but the fact that this is considered the normal correct way of doing things, is an indictment of c++ as a whole - and I say this as someone who uses c++ daily and who considers himself a safe and careful c++ programmer, who still occasionally makes mistakes due to things like this.
- jstimpfle 5y agoI find you're exaggerating what I don't recall has ever been an issue for me when doing C/C++. Having to compute sizes of dynamic objects in memory is just a normal thing to do. Here is a better practice btw: utf16_output.size()* sizeof utf16_output[0]; This removes the redundant indication of the element type (which can introduce bugs when the type of the array is changed). It gets even better when removing the naming slightly (names indicating types rarely make sense): out.size() * sizeof out[0]; With less magic: plain pointers instead of C++ vector like object, the following is total muscle memory for me: out_count * sizeof *out; I don't see how it is a problem having to do a simple multiplication when what's needed isn't the size that is normally used ("number of elements"), but the size in bytes of the slice. Adding some kind of syntax of library feature to remove this trivial multiplication would add more non-orthogonality, as one would now use sth like out.size_in_bytes() but for custom slices would have to do the calculation manually: n * sizeof out[0]; Note also that in the former case, the need to multiply is removed syntactically, but not at runtime. Personally I don't think there is a worthwhile improvement to have.
- jstimpfle 5y ago> and yet you still have to multiply the size of the container by the size of the data type inside the container in order to have correct behaviour. I'm also wondering what is the correct behaviour? In C++ you very very rarely want the size in bytes of a thing (much less often than in C), especially when implementing a generic container. In C++, every contained element could be a complex type with copy and move semantics and what not, so you should not just deal with plain memory.