0

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?

4
  • 1
    You could resize the std::string to the required length (std::string::resize()). Afterwards, you can copy the data into the std::string::data(). AFAIK, it is safe as long as you copy the appropriate size of chars. Commented Mar 23, 2020 at 14:29
  • 2
    FYI: SO: Is it permitted to modify the internal std::string buffer returned by operator[] in C++11 Commented Mar 23, 2020 at 14:32
  • 1
    @Scheff that worked by copying to &str.data()[0]. I'm surprised I couldn't use str.reserve() and i had to use str.resize() though but that's answered in stackoverflow.com/questions/9521629/… Commented Mar 23, 2020 at 14:33
  • 2
    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 if reserve() would provide the memory for granted - it's still not claimed to be in use.) Commented Mar 23, 2020 at 14:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.