首先我对这个问题感到抱歉。我已经在C++中查看了与delete
和new
相关的大多数主要答案,但我仍然无法在这里纠正我的问题。 这里我有3类,如下所示:在C++中正确使用删除
class bucket
{
// Some stl container here where data would be inserted
// Some methods and fields here
// This class has no new keyword
};
class TrieNode
{
public:
bucket *pointer;
TrieNode() //Constructor for this class
{
pointer = NULL;
};
TrieNode(int local) //Parametrized Constructor for this class
{
pointer = new bucket(local); //Here is the new keyword
}
};
class Hashtable
{
private:
int globalDepth;
std::vector<TrieNode> table; //Vector of other class
void Split(int index)
{
// Here I am creating instances of other class(TrieNode) which has pointer
TrieNode first(capacity);
TrieNode second(capacity);
// Then after some processing I have to do this
table[index] = first; //Assignment which will be using new keyword in it's class i.e. first
table[mirrorIndex] = second; //again assignment
}
public:
Hashtable(int globalDepth) //Constructor for this class
{
std::cout<<"Table is being created...\n";
this->globalDepth = globalDepth;
table.resize(pow(2,globalDepth),TrieNode()); //vector of class here
}
};
int main(int argc, char const *argv[])
{
bool input = true;
Hashtable mytable(1); //Instance of Third class
}
现在我的问题是,当我在
TrieNode
类使用析构函数与delete pointer
它让我尽快分段错误,我尝试在C级的载体插入一些因为析构函数创建后自动调用,它删除了向量吧?],当我在C类的析构函数为delete table[i].pointer
使用delete
然后我得到的错误太[核心转储。那么在这些情况下我应该如何使用delete
。我在一些函数中使用了一个类实例(带有new)的例子,例如在C类的Split函数中还是应该改变整体风格?
学习使用gdb并阅读std :: unique_ptr和复制构造函数(他们实际复制的内容) – James
@James Sure。谢谢! –