简体   繁体   English

C ++类模板初始化问题

[英]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 . 为了提供更多的上下文,我正在创建一个哈希表类,并在默认构造函数中,将数据初始化为nullptr ,在构造函数中使用size参数,将数据创建为new T * [size]并将每个元素设置为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. 在您的情况下, data将指向第二类中保留的数据。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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