」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > input: How Can I Construct Objects Using `std::malloc`? output: 使用`std::malloc`構造對象的正確姿勢

input: How Can I Construct Objects Using `std::malloc`? output: 使用`std::malloc`構造對象的正確姿勢

發佈於2025-04-15
瀏覽:508

 How Can I Construct Objects Using `std::malloc`? 
malloc and構造函數:探索指南

,標準庫同時提供std :: malloc and Malloc and New Expressions。儘管新的方便地通過構造函數初始化對象,但std :: malloc卻沒有。這提出了一個問題:我們如何創建一個對象並確保使用std :: malloc?

一種直接的方法是簡單地採用新表達式,因為它實現了預期的目的。但是,如果您更喜歡堅持使用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