まず、この質問は申し訳ありません。私は、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
}
今私の問題は、私は
delete pointer
とクラスTrieNode
でデストラクタを使用する場合、それは私はできるだけ早く私は、クラスCのベクトルで何かを挿入しようとして、障害をセグメンテーションを示していますデストラクタは作成後に自動的に呼び出され、ベクタ[right?]が削除され、クラスCデストラクタでdelete
を使用した場合、delete table[i].pointer
としてエラーが発生します。だから、どうすればdelete
を使うべきですか?たとえば、私がクラスインスタンスのいくつかの関数の中での(新しい)の割り当てを使用したケース。クラスCの上のスプリット関数で、ここで全体のスタイルを変更する必要がありますか?あなたが能力を定義しなかった
gdbの使い方を学び、std :: unique_ptrとコピーコンストラクタ(実際にコピーしたもの)について読む。 – James
@James確かに。ありがとう! –