title: How to most efficiently construct a std::string from char * with size
body: <p>I was looking at a way to achieve <code>sprintf()</code> functionality with <code>std::string</code> and I found a good answer from <a href="https://stackoverflow.com/a/8098080/369450">std::string formatting like sprintf</a>. This is somewhat hacky though because it writes directly to the pointer returned from <code>string.c_str()</code>. So I reimplemented it using a <code>char *</code> with <code>malloc()</code> and <code>realloc()</code>.</p>
  
  <pre><code>std::string string_format(const char * format, ...) {
      size_t size;
      size_t n;
      va_list args;
      char * buffer;
      std::string str;
  
      size = 100;
      buffer = malloc(size);
      for (;;) {
          va_start(args, format);
          n = vsnprintf(buffer, size, format, args);
          va_end(args);
          if (n &gt; -1) {
              if (n &lt; size) {
                  size = n;
                  break;
              }
              size = n + 1;
          } else {
              size *= 2;
          }
          buffer = realloc(buffer, size);
      }
  
      str = std::string(buffer, size);
  
      free(buffer);
      return str;
  }
  </code></pre>
  
  <p>I know I could just do:</p>
  
  <pre><code>str = std::string(buffer);
  </code></pre>
  
  <p>But then it will have to essentially do <code>strlen(buffer)</code>. I could make it a little better by:</p>
  
  <pre><code>str = std::string(buffer, size);
  </code></pre>
  
  <p>But would using <code>string.swap()</code> be more efficient by swapping the internal buffer instead of copying it?</p>
  
  <pre><code>str.swap(std::string(buffer, size));
  </code></pre>
  
  <p>Is there a better way to do this?</p>