malloc and構造函數:探索指南
一種直接的方法是簡單地採用新表達式,因為它實現了預期的目的。但是,如果您更喜歡堅持使用STD :: malloc,則有一種替代方法:使用稱為“位置新的新位置”的技術明確調用構造函數。 new允許我們在存儲位置在“存儲位置”中透露對象,請列出我們。要實現這一目標:使用std :: malloc為對象分配內存。
使用new(指針)在該位置初始化對象。 (類型*)malloc(sizeof(type)); new (pointer) type();
After creating the object, don't forget to destruct it using the explicit ~type() syntax and free the memory with free.
Here's a code snippet demonstrating placement new:
A* a = (A*)malloc(sizeof(A)); 新(a)a(); a-> 〜a(); Free(a);通過使用新的位置,您可以使用STD :: malloc創建對象,同時仍在調用構造函數。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3