単純な質問です。タイトルが示すように、私はクラスの新しいインスタンスを作成するために「new」演算子のみを使用したので、他の方法は何か、それを正しく使用する方法は何か疑問に思いました。
ベストアンサー1
また、自動を使用しないクラスのインスタンスはnew
、次のようにします。
class A{};
//automatic
A a;
//using new
A *pA = new A();
//using malloc and placement-new
A *pA = (A*)malloc(sizeof(A));
pA = new (pA) A();
//using ONLY placement-new
char memory[sizeof(A)];
A *pA = new (memory) A();
最後の2つは配置-新規これは、新しい. placement-newはコンストラクタを呼び出してオブジェクトを構築するために使用されます。3番目の例では、malloc
メモリを割り当てるだけで、コンストラクタは呼び出されません。配置-新規オブジェクトを構築するためにコンストラクターを呼び出すために使用されます。
メモリを削除する方法にも注意してください。
//when pA is created using new
delete pA;
//when pA is allocated memory using malloc, and constructed using placement-new
pA->~A(); //call the destructor first
free(pA); //then free the memory
//when pA constructed using placement-new, and no malloc or new!
pA->~A(); //just call the destructor, that's it!
新しい配置について詳しくは、次の FAQ をお読みください。
- 「新規配置」とは何ですか? また、なぜそれを使用するのですか?(parashift.com の FAQ)
- 配置新規(stackoverflow.com の FAQ)