Search code examples
c++memory-mapped-files

Create a std::string with fixed data location


Currently I have this going on:

struct HashItem {
    uint32_t Value;
    char Key;

    uint32_t GetSize() {
        return 4 + GetKey().size();
    }

    void SetKey(std::string &Key) {
        memcpy(&(this->Key), Key.c_str(), Key.size());
    }
    std::string GetKey() {
        return std::string(&Key);
    }

    static HashItem* Cast(void* p) {
        return reinterpret_cast<HashItem*>(p);
    }
};

That struct is meant to be an interpretation of a pointer location in a MMF. At the start of it, I have a hash table and right after it are those HashItems in series. I was wondering though if it was possible to create an std::string with a fixed char*(pointing to where the char Key currently is) for where it keeps the actual data?

That memory is manually managed anyway and having a string field instead of a char field would be more convenient.


Solution

  • ... if it was possible to create an std::string with a fixed char*(pointing to where the char Key currently is) for where it keeps the actual data?

    Not really - std::string explicitly and very clearly manages its own memory. You could perhaps hack it with a custom allocator, but I'm inclined to think it would be awful.

    If you just want something like a std::string (ie, having the same operators and public interface) but not owning its own memory, just use a Boost.String_Ref, which does what you (seem to) want without hacks.