所以我在C++呆了一小会儿后一直在闲逛。我试图破解一个动态映射类,它将std::string映射到任何对象类型。根据C++标准,static_casting *的指针可以保存地址。因此,如果我将给定的类型static_cast到一个空指针来存储它,并将它返回到原始类型的指针,那么我就不会有任何问题。下面是这门课的相关内容:
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++已经有几个月了,所以我对‘s 2012的例外有点生疏了。我不明白为什么在地图上插入大数的时候.在它生成异常之前的数字会在调试模式和发行版之间发生变化。
发布于 2014-05-20 03:30:29
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() ); https://stackoverflow.com/questions/23750512
复制相似问题