C++はので、ここで簡単に説明します、この分野でのJavaよりも非常に異なっています。
構成:オブジェクトは使用準備されています。
破壊:オブジェクトはすべてを「終了」し、自身を逆アセンブルします。
割り当て解除:メモリがシステムに戻されます。
機能が終了すると、(私たちは自動呼び出し)関数自体のすべての変数は、そのデストラクタが呼び出され
int main() {
int myint; //automatic int object is allocated and constructed
//stuff
} // when main ends, automatic int object is destroyed and deallocated
int main() {
int* mypointer; //automatic pointer object is allocated and constructed
mypointer = new int; //dynamic int object is allocated and constructed
//stuff
delete mypointer; //dynamic int object is destroyed and deallocated
} // when main ends, automatic pointer object is destroyed and deallocated
// note: Pointers to _not_ delete the object they point to.
class myclass {
//members
public:
myclass() {} //this is the default constructor
myclass(const myclass& rhs) {} //this is the copy constructor
myclass& operator=(const myclass& rhs) {return *this} //this is the assignment operator
~myclass() {} //this is the destructor
};
、その後、それらは自動的に解放されます。これは、関数のローカルオブジェクトを意味し、自動的に自身をクリーンアップします。インスタント関数が終了します。これは、クラスのメンバーにも魔法のように適用されます。それが破壊されると、それぞれのメンバーは自動的に破壊されます。これは、ほとんどのデストラクタが空であることを意味します。
手作業で(new
キーワードを使用して)手作業を割り当てる場合は、手作業でdelete
キーワードを使用して破棄して割り当てを解除する必要があります。 delete
に電話をかけると、すぐそこで破壊(および割り当て解除)され、完了するまで続行されません。あなたが忘れてしまった場合、プログラムが終了したときにオペレーティングシステムの一部が割り当て解除されます。
の人がミスをしているので、あなたが動的なオブジェクトを必要なときに行うには、「正しい」ものがある:
int main() {
std::unique_ptr<myclass> myptr = new myclass(); //allocate and construct
} //both the unique_ptr and the dynamic object are destroyed and deallocated
とunique_ptr
が大きくためにあなたを解放し、自動的にそれがで指すものをクリーンアップするのに十分なスマートです懸念
C++は、そのファイルを表すオブジェクトがF
の場合、そのファイルに排他ロックを設定する可能性があるためです。 C++では、一度F
が破壊されたら、すぐにを作成して、同じファイルを使用するオブジェクトG
を作成することができます。 Javaでは、finalizer
がになり、が実行されるという保証はなく、プログラムが終了するまでファイルがロックされたままである可能性があります。 (無理だろう、しかし可能)
C++はガベージコレクションを提供していません(実装することはできますが、お尻には本当の痛みがあり、通常は必要ありません)。代わりに[RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization)があり、デストラクタは非常に便利です。本を探す: –
C++とJavaは、車や列車とはまったく異なっています。 –
リンク先の記事を読んだことがありますか? C++にはガベージコレクタがありません。あなたの質問は意味をなさない。 –