4 ms·
That's the good thing about C. With C++, you don't know what is being allocated, where. With C, it is explicit. You know what's happening if you call malloc. A
by mike-cardwell 12y ago
That's the good thing about C. With C++, you don't know what is being allocated, where. With C, it is explicit. You know what's happening if you call malloc.
And this compose function could easily be written in C to take the "addr" as an argument to be filled, rather than provide it as a return value. Then it can be entirely stack allocated. The caller would need to make sure that the "addr" array was large enough of course.
I started learning C and C++ together at the same time a few years ago. I prefer to code in C++, using the standard template library, but there's always this extremely annoying little voice in the back of my head saying, "you could do this more efficiently if you operated on character arrays instead of a std::string"
- anthay 12y agoOn the other hand, I think one of the good things about C++ is that you have a choice. If you wish to write code that explicitly allocates memory for a string of characters you can. You can even wrap it up in a class to make it easy to use.
- pjmlp 12y ago> You know what's happening if you call malloc. You think you know what is happening. There are so many ways to implement malloc across OS and compilers. > "you could do this more efficiently if you operated on character arrays instead of a std::string" A bounds error waiting to happen at every string operation.
- humanrebar 12y ago> That's the good thing about C. With C++, you don't know what is being allocated, where. With C, it is explicit. You're complaining about allocation in the C++ standard library. How many allocations does sqlite3_open_v2 make? How about git_repository_open? C code hides allocation just as much as C++ code does. Only C++ provides simple mechanisms (destructors) to make sure everything gets cleaned up when the stack unwinds. I'll agree that std::string does the wrong thing here. The C++ standard library gets strings wrong in a lot of ways. That's why vector usually provides better examples.