简体   繁体   中英

Problems with C++ Class Template Initialization

Can someone explain to me why...

DataStructure<MyClass> ds;

cin >> size;
ds = DataStructure<MyClass>(size);

causes my program to crash, but...

cin >> size;
DataStructure<MyClass> ds = DataStructure<MyClass>(size);

does not?

I think it has something to do with my program using the default constructor and followed by an attempt to use the implicit copy constructor but I am not sure.

To give more context, I'm creating a hash table class and in the default constructor, I initialize the array with data to nullptr and in the constructor with the size argument, I create the array with the data to new T * [size] and set each element to nullptr .

Constructor without any parameters:

this->data = nullptr;

vs.

Constructor with size parameter:

this->data= new T * [size];
for(int i = 0; i< size; i++)
{
    data[i] = nullptr;
}

You will need to declare a copy constructor. If you do not have a copy constructor then all members will be copied. In your case data will point to the data reserved in the second class. Next, this data will be destroyed together with the class and points to nothing. That will most likely cause your program to crash. Your copy constructor should do deep copy, something like this:

DataStructure(const DataStructure &rhs)
{
    if (this->data) delete[] data;
    this->data = new T*[rhs.GetSize()];
    for (int i=0; i<rhs.GetSize(); i++)
    {
        this->data[i] = rhs.data[i];
    }
    return *this;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM