資源簡介
C++內存管理,在侯捷老師教授下,深入理解C++內存機制。
代碼片段和文件信息
//?author?:?Hou?Jie?(侯捷)
//?date?:?2015/11/11?
//?compiler?:?DevC++?5.61?(MinGW?with?GNU?4.9.2)
//
//?說明:這是侯捷?E-learning?video?“C++內存管理“?的實例程式.
//?該課程的所有測試都出現在此.
//?每一個小測試單元都被放進一個?namespace?中?
//?如此保持各單元間最大的獨立性.
//?每個?namespace?上方皆有該單元相應的?#include?<...>?
//?因此有可能整個程式重複含入?(included)?某些?headers??
//?這無所謂,因為每個?standard?headers?都有自我防衛機制,不讓自己被?included?二次.
//
//?本文件用到若干?GNU?C++?extended?allocators,所以你或許需要在你的集成環境?(IDE)?上設定?“C++11?on“.?
//?我已將相關代碼包裝在?編譯條件選項?__GNUC__?中。?
/*
#include?
#include?
#include??
#include??//strlen()
#include?
#include?
*/
using?namespace?std;
//----------------------------------------------------
#include?
#include?
#include? ?//std::allocator??
#include? ?//欲使用?std::allocator?以外的?allocator?就得自行?#include??
namespace?jj01
{
void?test_primitives()
{
cout?<“\ntest_primitives()..........?\n“;
????void*?p1?=?malloc(512); //512?bytes
????free(p1);
????complex*?p2?=?new?complex;?//one?object
????delete?p2;?????????????
????void*?p3?=?::operator?new(512);?//512?bytes
????::operator?delete(p3);
//以下使用?C++?標準庫提供的?allocators。
//其接口雖有標準規格,但實現廠商並未完全遵守;下面三者形式略異。
#ifdef?_MSC_VER
????//以下兩函數都是?non-static,定要通過?object?調用。以下分配?3?個?ints.
????int*?p4?=?allocator().allocate(3?(int*)0);?
????allocator().deallocate(p43);???????????
#endif
#ifdef?__BORLANDC__
????//以下兩函數都是?non-static,定要通過?object?調用。以下分配?5?個?ints.
????int*?p4?=?allocator().allocate(5);??
????allocator().deallocate(p45);???????
#endif
#ifdef?__GNUC__
????//以下兩函數都是?static,可通過全名調用之。以下分配?512?bytes.
????//void*?p4?=?alloc::allocate(512);?
????//alloc::deallocate(p4512);???
????
????//以下兩函數都是?non-static,定要通過?object?調用。以下分配?7?個?ints.????
void*?p4?=?allocator().allocate(7);?
????allocator().deallocate((int*)p47);?????
????//以下兩函數都是?non-static,定要通過?object?調用。以下分配?9?個?ints.
void*?p5?=?__gnu_cxx::__pool_alloc().allocate(9);?
????__gnu_cxx::__pool_alloc().deallocate((int*)p59);
#endif
}
}?//namespace
//----------------------------------------------------
#include?
#include?
//#include? ?//std::allocator??
namespace?jj02
{
class?A
{
public:
??int?id;
??
??A()?:?id(0)??????{?cout?<“default?ctor.?this=“??<??A(int?i)?:?id(i)?{?cout?<“ctor.?this=“??<??~A()?????????????{?cout?<“dtor.?this=“??<};
void?test_call_ctor_directly()
{
cout?<“\ntest_call_ctor_directly()..........?\n“;
????string*?pstr?=?new?string;
????cout?<“str=?“?<*pstr?<????
//!?pstr->string::string(“jjhou“);??
????????????????????????//[Error]?‘class?std::basic_string‘?has?no?member?named?‘string‘
//!?pstr->~string(); //crash?--?其語法語意都是正確的?crash?只因為上一行被?remark?起來嘛.??
????cout?<“str=?
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件?????1647346??2015-11-17?19:23??C++內存管理示例.exe
?????文件??????184322??2015-12-23?17:20??C++內存管理簡介-侯捷.pdf
?????文件????36386090??2015-12-23?15:45??內存管理.pdf
?????文件?????7959780??2015-12-23?17:40??內存管理第五講.pdf
?????文件???????15850??2015-11-17?19:23??allocc.h
?????文件???????96268??2015-11-17?19:23??C++內存管理示例.cpp
評論
共有 條評論