Dealing with char buffers

前端 未结 9 1532
情书的邮戳
情书的邮戳 2021-02-08 02:33

As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:

char buffer[512];
sprintf(buffer, \"Hello %s!\", userName.c_s         


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 02:52

    • It's up to you, just doing buffer is more terse but if it were a vector, you'd need to do &buffer[0] anyway.
    • Depends on your intended platform.
    • Does it matter? Have you determined it to be a problem? Write the code that's easiest to read and maintain before you go off worrying if you can obfuscate it into something faster. But for what it's worth, allocation on the stack is very fast (you just change the stack pointer value.)
    • You should be using std::string. If performance becomes a problem, you'd be able to reduce dynamic allocations by just returning the internal buffer. But the std::string return interface is way nicer and safer, and performance is your last concern.
    • That's a memory leak. Many will argue that's okay, since the OS free's it anyway, but I feel it terrible practice to just leak things. Use a static std::vector, you should never be doing any raw allocation! If you're putting yourself into a position where you might leak (because it needs to be done explicitly), you're doing it wrong.
    • I think your (1) and (2) just about cover it. Dynamic allocation is almost always slower than stack allocation, but you should be more concerned about which makes sense in your situation.
    • You shouldn't be using those at all. Use std::string, std::stringstream, std::copy, etc.

提交回复
热议问题