一、使用new關鍵字新建單個對象管理動態內存
class Person { public: Person() { cout << "Person object created!" << endl; } ~Person() { cout << "Person object destroyed!" << endl; } }; int main() { Person* p = new Person(); // 使用new關鍵字創建Person對象 // 使用p指針訪問Person對象的成員函數和成員變量 delete p; // 刪除使用new創建的對象 return 0; }
使用new關鍵字來動態分配內存空間,可以根據當前程序的需求大小靈活分配,在程序運行時根據需要釋放已經使用的資源。但是在使用完動態內存後,一定要使用delete關鍵字來釋放已經使用的資源,否則會導致內存泄漏。
二、使用new關鍵字新建數組管理動態內存
class Person { public: Person() { cout << "Person object created!" << endl; } ~Person() { cout << "Person object destroyed!" << endl; } }; int main() { Person* p = new Person[5]; // 使用new關鍵字創建Person對象的數組 // 使用p指針訪問Person對象數組的成員函數和成員變量 delete[] p; // 刪除使用new創建的對象數組 return 0; }
在使用new來創建數組管理動態內存時,需要使用delete[]來釋放動態分配的內存,因為使用new來創建數組而沒有使用delete[]來釋放內存會導致內存泄漏。
三、使用智能指針管理動態內存
#include class Person { public: Person() { cout << "Person object created!" << endl; } ~Person() { cout << "Person object destroyed!" << endl; } }; int main() { shared_ptr p = make_shared(); // 使用make_shared函數創建智能指針 // 使用p指針訪問Person對象的成員函數和成員變量 return 0; // 函數結束時智能指針會自動釋放內存 }
智能指針可以自動釋放內存空間,在指針對象生命周期結束時自動調用析構函數。C++11的標準庫中提供了兩種智能指針,shared_ptr和unique_ptr。shared_ptr和unique_ptr的區別在於,shared_ptr可以和多個指針共享同一個對象,而unique_ptr則只能指向一個對象。
四、使用RAII技術實現動態內存管理
class Resource { public: Resource() { cout << "Resource acquired!" << endl; } ~Resource() { cout << "Resource released!" << endl; } }; class RAII { public: RAII() { pResource = new Resource(); } ~RAII() { delete pResource; } private: Resource* pResource; }; void func() { RAII obj; // 在RAII對象構造時申請資源,在RAII對象析構時釋放資源 } int main() { func(); // func函數執行結束後,RAII對象會自動釋放資源 return 0; }
RAII(Resource Acquisition Is Initialization)技術是一種常用的動態內存管理技術,RAII對象用於在其構造函數中申請資源,在其析構函數中釋放資源。使用RAII技術可以避免動態內存管理錯誤和內存泄漏。
五、使用容器管理動態內存
#include class Person { public: Person() { cout << "Person object created!" << endl; } ~Person() { cout << "Person object destroyed!" << endl; } }; int main() { vector v; // 使用vector容器管理Person對象 v.push_back(Person()); // 在vector中添加Person對象 return 0; // 函數結束時vector容器會自動釋放內存 }
C++標準庫提供了多種容器類來管理動態內存,vector是其中一種容器,它可以自動管理內存並為程序員提供簡單的語法來添加、刪除、訪問元素。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/158045.html