c++ - 创建具有固定数据位置的 std::string

标签 c++ memory-mapped-files

目前我正在做这件事:

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);
    }
};

该结构旨在解释 MMF 中的指针位置。在它的开头,我有一个哈希表,紧随其后的是那些串联的 HashItems。我想知道是否可以创建一个带有固定 char*(指向 char 键当前所在的位置)的 std::string 来保存实际数据?

无论如何,内存都是手动管理的,使用字符串字段而不是字符字段会更方便。

最佳答案

... 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?

不是真的 - std::string 明确且非常清楚地管理它自己的内存。您或许可以使用自定义分配器破解它,但我倾向于认为这会很糟糕。

如果您只是想要类似std::string(即具有相同的运算符和公共(public)接口(interface))但不拥有自己的内存,只需使用 Boost.String_Ref ,无需黑客即可完成您(似乎)想要的事情。

关于c++ - 创建具有固定数据位置的 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743714/

相关文章:

c++ - c++ 根据时间创建对象

c++ - opencv3 中贝叶斯和支持 vector 机分类器的实现

c++ - operator new inside 命名空间

c++ - boost::iostreams::mapped_file_sink 抛出未知异常

c++ - boost Mapped_file_source 会抛出哪些异常?

c# - 使用 MemoryMappedViewAccessor 错误编写打包结构?

c++ - 使用没有定义的函数c++合法吗?

c++ - 递归STL映射

android - 如何在 Linux 平台上管理 mmap 的内存使用?

c - 内存映射文件