将中等数量的T*静态强制转换为void*时发生访问冲突
Access violation when static_casting a mid-sized number of T* to void*
所以我在中断了一段时间后一直在c++中闲逛。我试图破解一个动态映射类,将std::字符串映射到任何对象类型。根据c++标准的static_casting,指向和来自void*的指针会保留地址。因此,如果我将给定的类型静态转换为一个void指针来存储它,然后再将其静态转换回原始类型的指针,应该不会有任何问题。下面是类的相关内容:
template<class T>
T& get( const std::string& key )
{
return *static_cast<T*>( _data[ key ] );
}
template < typename T >
void put( const std::string& key, const T& val )
{
T* typePointer = new T( val );
_data[ key ] = static_cast<void*>( typePointer );
}
std::map< std::string, void* > _data;
对于非指针参数,这些方法都工作得很好,我想看看put/get开销与静态类型std::map的开销的比较。但是,当插入大量对象时,我会得到"访问违反读取位置"错误。
// this works
DynamicMap myMap1;
for (uint i=0; i<100; i++)
{
myMap1.put( "mat"+i, MyClass() );
}
// this doesn't
DynamicMap myMap2;
for (uint i=0; i<100000; i++)
{
myMap2.put( "mat"+i, MyClass() );
}
自从我接触c++已经有几个月了,所以我对VS2012的异常有些生疏。我不明白为什么在地图中插入大量数字时会发生这种情况……在Debug模式和Release模式之间,生成异常之前的数字会发生变化。
warning: adding 'int' to a string does not append to the string
您的"mat"+i
没有创建一个末尾附加i
的新字符串,因此您最终弄乱了键。使用"mat" + std::to_string(i)
(c++ 11),或者
stringstream ss;
ss << i;
string i_string = ss.str();
myMap2.set( "mat"+i_string, MyClass() );
相关文章:
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- Boost buffer_cast 无法从 void* 转换为 PointerToPodType
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 在不同的编译器上转换为 void**
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 不能在 if 语句 - c++ 中使用 void func 直接将字符串转换为大写
- 是否可以将已经初始化的变量转换为 void*?
- 错误:从'void*'到'const uint8_t* {aka const unsigned char*}'的转换无效 [-允许]
- 将可变参数模板类型转换为 void,预期')'之前
- 如何在运行时将指向派生类的 void* 正确转换为指向基类的 void*
- 是否强制转换void**并将第一个字节设置为nullptr
- 如何转换 void* 以访问结构的静态数据成员?
- 警告传递"double"以转换"void moveto(int, int)"的 2
- 是否有一种方法可以自动转换void指针的类型
- 在构造函数中强制转换void*并访问值
- 重新解释不带类型标识符的强制转换void
- 强制转换void指针