我一直在尝试为线程之间的共享访问提供一个容器。而且我认为我正在寻找的东西看起来像这样:
std::map<int, std::array<char, 256>>msg_buffers; //make atomic
线程将用来中继信息的(原子)
array<char,256>
的映射。事实是,我发现我只能将值复制到映射所引用的数组中,并且它们的出现就像我正常添加元素一样。我感觉这会在以后导致问题,我很好奇为什么它不会引起错误,或者为什么它会起作用。看起来是这样的:
#include <array>
#include <map>
std::map<int, std::array<char, 256>>charmap; //a msg queue
char charbuf[256]; //incoming msg buffer
for (int x = 0; x < 256; x++)charbuf[x] = '0'; //make arbitrary msg
//memcopy arbitrary msg **directly** to array at (non existing) map[4]
memcpy(charmap[4].data(), charbuf, sizeof(char) * 256);
//which will then magically exist
std::cout << "Used slots in charmap are: ";
if (!charmap.empty())
for (auto x : charmap)std::cout << x.first << " | "; //cout existing elements
即使我没有专门创建元素,添加了
memcpy()
的元素也将正常显示。这是编译器在我不知情的情况下执行的操作吗?我看不到这是一种向 map 添加元素的方法,我认为它应该发出某种警告。我使用Visual Studio 2017对此进行了编译。
最佳答案
charmap[4]
通过键4
返回对该值的引用(如果尚不存在,它将自动创建该元素)。该值的类型为std::array<char, 256>
,可以正常操作。 memcpy只是将内容复制到此缓冲区中,并且memcpy没有神奇之处。特别是,它不会创建新元素。
关于c++ - 为什么memcpy()是将元素添加到 `std::map`的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45863832/