I currently have this (pseudo) code
private:
uint8_t* m_aBuf;
public:
template <>
auto read<std::string>() -> std::string
{
auto usLength = this->decode<uint16_t>();
auto pStr = std::make_unique<char[]>(usLength);
std::copy(this->m_aBuf, this->m_aBuf + usLength, &pStr.get()[0]);
return std::string(pStr);
}
Assuming the buffer looks like this:
05 00 68 65 6c 6c 6f
My expectation is for the specialized read<std::string>() to return a C++ string containing "hello". The size of the string is known during run time of the function (it's usLength).
(Yes I'm aware this will only work on little-endian systems and that's fine)
My intention is to avoid having the overhead of allocating the char[] array.
Can I do that? And how? Or is there a better solution for what I'm trying to achieve?
std::stringto the required length (std::string::resize()). Afterwards, you can copy the data into thestd::string::data(). AFAIK, it is safe as long as you copy the appropriate size ofchars.&str.data()[0]. I'm surprised I couldn't usestr.reserve()and i had to usestr.resize()though but that's answered in stackoverflow.com/questions/9521629/…std::string::reserve()is not the right tool for this.std::string::resize()grants that the internal buffer provides at least the required size (if it doesn't fail). So, the internal buffer of size must be there afterwards, which makes the little raw-overwrite-trick safe. (Even ifreserve()would provide the memory for granted - it's still not claimed to be in use.)