首先我很抱歉这个问题。我已经查看了大多数与 C++ 中的 delete
和 new
相关的主要答案,但我仍然无法在此处纠正我的问题。
这里我有 3 个类如下:
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
}
Now my problem is when I use destructor in class
TrieNode
withdelete pointer
it shows me segmentation fault as soon as I try to insert something in the vector of class C because destructor is called automatically after the creation and it deletes the vector [right?] and when I usedelete
in the class C destructor asdelete table[i].pointer
then I get the error too [core dumped]. So how should I usedelete
in these cases. Cases where I have used assignment of a class instance (with new) inside some functions for e.g. in Split function above in class C Or should I change the overall style here?
最佳答案
A TrieNode
实例拥有它的 pointer
bucket
类型的实例, 因此它负责通过调用 delete
来释放它在析构函数中。所以首先你需要添加如下内容:
~TrieNode()
{
delete pointer;
}
(请注意,pointer
可能不是变量的好名称,因为它指示其类型而不是其用途。考虑 data
或其他名称。)
然后每当 TrieNode
被删除,它的桶指针也将被删除。您可以调用delete
安全地 nullptr
它什么都不做,所以没有必要测试 pointer
是否存在。已设置。
由于哈希表使用 std::vector<TrieNode>
的实例, vector 将包含(并拥有)对象实例。因此删除一个实例,删除 HashTable
等都应该正确清理。
一个潜在的问题是如果您创建一个 TrieNode
的实例然后将其传递给 HashTable
.这将生成对象的浅表拷贝(因为您尚未定义复制构造函数),因此您将有两个对象指向堆上的同一个桶。当第一个实例被销毁时,桶将被删除。但是当第二个实例被销毁时,它同样会尝试第二次删除桶,并导致崩溃。我怀疑这可以解释您描述的崩溃问题。
一般来说,如果你的类动态分配内存,它应该有一个析构函数和一个复制构造函数,以便正确管理内存。尝试使新/删除对称工作,所以拥有内存的东西(调用 new
)也是 delete
是它。哈希表不应该“进入”trie 对象并代表它删除内存。
正如@James 上面评论的那样,使用智能指针并让编译器和库为您完成工作可能是值得的。
关于c++ - 在c++中正确使用delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182925/