Reading directly from an std::istream into an std::string

后端 未结 6 1059
误落风尘
误落风尘 2020-11-30 08:00

Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so?

eg currently I can do it by



        
6条回答
  •  被撕碎了的回忆
    2020-11-30 08:41

    Are you just optimizing code length or trying to save yourself a copy here? What's wrong with the temporary buffer?

    I'd argue that you're actually circumventing the protections of the string trying to write directly do it like that. If you're worried about performance of the copy to a std::string because you've identified that it's in some way affecting the performance of your application, I'd work directly with the char*.

    EDIT: Doing more looking... initializing std::string from char* without copy

    In the second answer, it's stated pretty flatly that you can't achieve what you're looking to achieve (ie. populate a std::string without an iteration over the char* to copy.)

    Take a look at your load routine (post it here perhaps?) and minimize allocations: new and delete certainly aren't free so you can at least save some time if you don't have to re-create the buffer constantly. I always find it helpful erase it by memset'ing the buffer to 0 or null terminating the first index of the array each iteration but you may quickly eliminate that code in the interests of performance once you're confident in your algorithm.

提交回复
热议问题