代码改变世界

new placement 的使用

2014-01-18 21:27  hongjiumu  阅读(305)  评论(0编辑  收藏  举报
#include <iostream> 
  
#include "TModel.h" 
  
int main() 
{ 
    char * p_char=new char[100]; 
    std::cout<<"Source Location = "<<unsigned(p_char)<<std::endl; 
    TModel * pTModel; 
    pTModel=new (p_char)TModel; 
    pTModel->Show(); 
    delete pTModel; 
  
  
    //The Second Part. 
    TModel * pTModel2=(TModel *)(new char[sizeof(TModel)]); 
  
    //If omitted,<Bad Ptr> 
    //at    std::cout<<"Location = "<<unsigned(this) 
    //  <<" , Name = "<<m_sName 
    //  <<std::endl; 
    pTModel2=new (pTModel2)TModel; 
  
    std::cout<<"Source 2 Location = "<<unsigned(pTModel2)<<std::endl; 
    pTModel2->Show(); 
    delete pTModel2; 
  
  
    getchar(); 
  
    return 0; 
}; 
#include "TModel.h" 
#include <iostream> 
  
void TModel::Show() 
{ 
    std::cout<<"Location = "<<unsigned(this) 
        <<" , Name = "<<m_sName 
        <<std::endl; 
}; 
  
TModel::TModel() 
{ 
    m_sName="Hello"; 
}; 
  
TModel::~TModel() 
{ 
  
};