I have this assignment for homework, which consists of me implementing a buffer optimization to a string class. I have to save the pointer from bytes 8 to 16, because the first byte is used to see if the string is heap-allocated or stack-allocated, and bytes 1-7 are used to save the length of the string. I need help finding out how I can save a pointer to dynamically allocated memory and then return it from bytes 8-16.
How I create the buffer:
alignas(CharT) std::array<std::byte, SZ> buffer;
How I want to return the buffer:
return reinterpret_cast<CharT *>(buffer[8]);
I tried to use memcpy()
and memmove()
, but when I do that I am able to return only 8 bytes from the original string.
How I create and manipulate the pointer:
auto ptr = ::operator new[](count_bytes, std::align_val_t{std::alignment_of_v<CharT>});
std::memcpy(ptr, sv.data(), count_bytes);
std::memmove(&buffer[8], ptr, sizeof(ptr));
The implementation of the buffer:
template<typename CharT = char, std::size_t SZ = 32>
struct storage {
private:
alignas(CharT) std::array<std::byte, SZ> buffer;
public:
void set(const std::basic_string_view<CharT> &sv) {
std::size_t count_bytes = sizeof(CharT) * (sv.length() + 1); ///counts the bytes of the string
auto ptr = ::operator new[](count_bytes, std::align_val_t{std::alignment_of_v<CharT>}); /// make a pointer to the memory location
std::memcpy(ptr, sv.data(), count_bytes);
std::memmove(&buffer[8], &ptr, sizeof(ptr));
operator delete[](ptr);
}
const CharT *str() {
/// Returs a pointer to the first byte of the string
return reinterpret_cast<CharT *>(buffer[8]);
}