首先我對這個問題感到抱歉。我已經在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。謝謝! –