zoukankan      html  css  js  c++  java
  • 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指针使用

  • 相关阅读:
    owlsuddimatchmaker安装
    类集
    jsp基本语法
    心得思路记录下
    nyoj517 最小公倍数
    poj1250 Tanning Salon
    poj1686 Lazy Math Instructor
    poj3250 Bad Hair Day
    poj1047 Round and Round We Go
    poj2359 Questions
  • 原文地址:https://www.cnblogs.com/lailailai/p/3657570.html
Copyright © 2011-2022 走看看