I'm struggling with my copy constructor and assignment operator in my C++ program. I get a segmentation fault (core dump) when testing either of them, individually. I'm building a hash table that is constructed through an array with a pair inside each index. The indexes are chosen based on a hash function, the first part of the pair is a key, the second part of the pair is a value. There's obviously more to the class, but nothing that affects the copy and assignment operator, so I kept them out there. I have no memory leaks and I test the op= and copy constructor with a good number of values already in it.
In UnorderedMap.h
template <typename K, typename V>
class MyUnorderedMap: public Dictionary<K, V>
{
private:
MyPair<K, V> *m_data = nullptr; // hash table, array of pairs
int data_size = 0; // current number of elements inside the array
int reserved_size = 0; // max elements inside the array
public:
// Start data_size and reserved_size at 0, m_data to nullptr
MyUnorderedMap();
~MyUnorderedMap();
MyUnorderedMap(const MyUnorderedMap<K, V> &source);
MyUnorderedMap<K, V> & operator=(const MyUnorderedMap<K, V> &source);
}
In UnorderedMap.hpp
// Copy Constructor
template <typename K, typename V>
MyUnorderedMap<K, V>::MyUnorderedMap(const MyUnorderedMap<K, V> &source)
{
data_size = source.data_size;
reserved_size = source.reserved_size;
m_data = new MyPair<K, V>[reserved_size];
for(int i = 0; i < reserved_size; i++)
{
m_data[i].first = source.m_data[i].first;
m_data[i].second = source.m_data[i].second;
}
}
// Assignment Operator
template <typename K, typename V>
MyUnorderedMap<K, V> & MyUnorderedMap<K, V>::operator=(const MyUnorderedMap<K, V> &source)
{
if(this!=&source)
{
delete[] m_data;
reserved_size = source.reserved_size;
data_size = source.data_size;
m_data = new MyPair<K, V>[reserved_size];
for(int i=0; i<reserved_size; i++)
{
m_data[i].first = source.m_data[i].first;
m_data[i].second = source.m_data[i].second;
}
}
return *this;
}
In MyPair.h
template <typename K, typename V>
struct MyPair
{
K first;
V second;
MyPair(){}
MyPair(const K &key): first(key) {}
MyPair(const K &key, const V &value): first(key), second(value) {}
};
Does anyone see a problem with why it would be behaving like this? I'm a lot more confident in my copy constructor than the operator=.
Edit x3: I have an insert function not shown that properly inserts into the hash table. So I solved the copy constructor but the op= is still not working.. I fixed the copy constructor above so now it shows a working copy constructor, for anyone else who wants to use it as an effectively working basis. Fixed the assignment operator as well and provided the correct version.