だから私はc++を学ぼうとしている小さなプロジェクトのために私のニーズにかなり特化したハッシュマップを作成しようとしています。私は次のコードを持っています:
template<class T>
class HashMap
{
public:
HashMap();
virtual ~HashMap();
void add(T value);
T get(T *value);
private:
int hash(T *data);
T _hashes[26]; //I want a fixed size here
};
template<class T>
HashMap<T>::HashMap()
{
for(int i = 0; i < 26; i++)
this->_hashes[i] = T();
}
template<class T>
HashMap<T>::~HashMap()
{
//Don't really have anything to delete here?
}
template<class T>
int HashMap<T>::hash(T *dat)
{
//Super simple, just to try things out
return (long int) dat % 26;
}
template<class T>
T HashMap<T>::get(T *val)
{
int idx = this->hash(val);
cout << idx << endl;
//Probably somewhere here i get my problem
if(this->_hashes[idx])
return this->_hashes[idx];
return T();
}
template<class T>
void HashMap<T>::add(T val)
{
//Should probably do some check if there's already an element here.
this->_hashes[this->hash(&val)] = val;
}
私が抱えている問題は、これが正常にコンパイルされることですが、main.cppでこのようなことをすると:
HashMap<char> a = HashMap<char>();
a.add('h');
a.add('c');
a.add('g');
char *b = new char {'c'};
cout << a.get(b) << endl;
delete b;
通常、IDを返します。
4
そして、空の文字である空の行。(関数の出力はget()メソッドにあります)が、次のようなものが表示される場合があります。
18
g
18と空の行の代わりに。私の質問は、なぜこれが起こるのか、そしてどうすればそれを防ぐことができるのかということです。削除されたときにメモリが「null」にならず、他のプログラムが自由に使用できるようになっていて、正しく初期化されないことと関係がありますか?また、時間があれば、コード内で間違いを指摘したり、うまくいかなかったりすることを指摘してください。
GCC Debian 4.4.5-8を使用してコンパイルし、g ++ -gfile.cpp-oファイルでコンパイルすることに関心がある場合
助けてくれてありがとう!