gpt4 book ai didi

c++ - 从 Visual C++ 中的 unordered_map 继承时,模板参数的 sizeof() 不正确

转载 作者:行者123 更新时间:2023-11-30 02:31:45 24 4
gpt4 key购买 nike

当声明一个继承自 std::unordered_map 的类模板时,我在 Visual C++ 2015 中运行时得到错误的模板参数大小。

下面的代码在 Ubuntu 64 位上按预期工作,当编译时

g++ -std=c++11 test.cpp

输出如下:

OUTSIDE: sizeof(my_key_type) = 12, sizeof(my_value_type) = 24
INSIDE: sizeof(my_key_type) = 12, sizeof(my_value_type) = 24
INSIDE(WTF?): sizeof(key_type) = 12, sizeof(value_type) = 24

但是在 64 位机器上的 Visual C++ 2015 中,我得到:

OUTSIDE: sizeof(my_key_type) = 12, sizeof(my_value_type) = 24
INSIDE: sizeof(my_key_type) = 12, sizeof(my_value_type) = 24
INSIDE(WTF?): sizeof(key_type) = 12, sizeof(value_type) = 40

如果我不从 std::unordered_map 继承,那么在 Ubuntu 和 VC2015 上一切正常。我在这里缺少什么?

预先感谢您的帮助 - 这是代码:

#include <stdio.h>
#include <string.h>
#include <string>
#include <unordered_map>

class my_key_type {
unsigned int _int1;
unsigned int _int2;
unsigned short _short1;
unsigned short _short2;
public:
bool operator == (const my_key_type &other_key) const {
return (memcmp(this, &other_key, sizeof(my_key_type)) == 0);
};
};

namespace std {
template <> struct hash<my_key_type> {
std::size_t operator()(const my_key_type &key) const {
return std::hash<string>()(std::string((const char *)&key, sizeof(my_key_type)));
};
};
};

class my_value_type {
bool _flag;
unsigned long long _count1;
unsigned long long _count2;
};

#define INHERITS_FROM_UNORDERED_MAP 1
#if (INHERITS_FROM_UNORDERED_MAP == 0)
template <typename key_type, typename value_type> class kv_map {
#else
template <typename key_type, typename value_type> class kv_map : public std::unordered_map<key_type, value_type> {
#endif
public:
void test_print() {
printf("INSIDE: sizeof(my_key_type) = %ld, sizeof(my_value_type) = %ld\n", sizeof(my_key_type), sizeof(my_value_type));
printf("INSIDE(WTF?): sizeof(key_type) = %ld, sizeof(value_type) = %ld\n", sizeof(key_type), sizeof(value_type));
};
};

int main() {
printf("OUTSIDE: sizeof(my_key_type) = %ld, sizeof(my_value_type) = %ld\n", sizeof(my_key_type), sizeof(my_value_type));
kv_map<my_key_type, my_value_type> map;
map.test_print();
};

最佳答案

std::unordered_map 有一个类型叫做 value_type

value_type  std::pair<const Key, T>

几乎可以肯定的是,您正在选择它 - 因为它也包括关键数据。

更改模板类型的名称,看看会发生什么。

关于c++ - 从 Visual C++ 中的 unordered_map 继承时,模板参数的 sizeof() 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37235654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com