「new」演算子を使用せずにクラスの新しいインスタンスを作成する 質問する

「new」演算子を使用せずにクラスの新しいインスタンスを作成する 質問する

単純な質問です。タイトルが示すように、私はクラスの新しいインスタンスを作成するために「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 をお読みください。

おすすめ記事