如何动态创建大量的小对象,同时又避免内存碎片呢?这里先把MSDN的一个例子贴出来,有时间再过来和大家解释,最近很忙,谅解,谅解:
- // new_op_new.cpp
- // compile with: /EHsc
- #include<new>
- #include<iostream>
- using namespace std;
- class MyClass
- {
- public:
- MyClass( )
- {
- cout << "Construction MyClass." << this << endl;
- };
- ~MyClass( )
- {
- imember = 0; cout << "Destructing MyClass." << this << endl;
- };
- int imember;
- };
- int main( )
- {
- // The first form of new delete
- MyClass* fPtr = new MyClass;
- delete fPtr;
- // The second form of new delete
- MyClass* fPtr2 = new( nothrow ) MyClass;
- delete fPtr2;
- // The third form of new delete
- char x[sizeof( MyClass )];
- MyClass* fPtr3 = new( &x[0] ) MyClass;
- fPtr3 -> ~MyClass();
- cout << "The address of x[0] is : " << ( void* )&x[0] << endl;
- }