Effective C++ Placement new
1 #include <iostream> 2 #include <cstdlib> 3 4 using namespace std; 5 6 class Card { 7 private: 8 int m_SerialNumber; 9 public: 10 Card(int id) : m_SerialNumber(id) {} 11 ~Card() {cout<<"~Card"<<endl;} 12 void print() {cout<<m_SerialNumber<<endl;} 13 }; 14 15 int main() { 16 int num = 10; 17 void *rawMemory = operator new[](num * sizeof(Card)); 18 Card *cards = static_cast<Card*>(rawMemory); 19 20 for (int i=0; i<num; i++) { 21 new(&cards[i]) Card(i+1); 22 } 23 24 for (int i=0; i<num; i++) { 25 cards[i].print(); 26 } 27 28 for (int i=num-1; i>=0; i--) { 29 cards[i].~Card(); 30 } 31 operator delete[](rawMemory); 32 system("pause"); 33 return 0; 34 }
这么奇葩的操作。
operator delete[] 只能对由对应 operator new[] 得到的空间指针变量操作,不能直接对cards指针使用