lundi 3 juin 2019

Is that good behavior to use std::string as buffer?

I have recently seen a colleague of mine uses std::string as a buffer as below:

std::string receive_data(const Receiver& receiver) {
  std::string buff;
  int size = receiver.size();
  if (size > 0) {
    buff.resize(size);
    const char* dst_ptr = buff.data();
    const char* src_ptr = receiver.data();
    memcpy((char*) dst_ptr, src_ptr, size);
  }
  return buff;
}

I guess this guy wants to take advantage of auto destruction of the returned string so he needs not worry about freeing of the allocated buffer.

This looks a bit strange to me since according to CPP Reference the data() method returns a const char* pointing to a buffer internally managed by the string:

const char* data() const noexcept;

Memcpy-ing to a const char pointer ? AFAIK this does no harm as long as we know what we do, but is a good behavior and why?

Aucun commentaire:

Enregistrer un commentaire