防止内存泄露

Posted on 2008-12-01 01:00 蓝尘 阅读(133) 评论(0)  编辑 收藏 引用
1.常规方法
示例:
  void userCode(const char* s1, const* s2)
  {
      char* copy = new char[strlen(s1)+1];
      strcpy(copy,s1);
 
      //用try块来防止内存泄露
      try{
          //.
          delete[] copy;
         char *copy = new char[strlen(s1)+strlen(s2)+1];
         strcat(copy,s1);
         strcat(copy,s2);
         //
         }catch(){
            delete[] copy;
            throw;
     }
     delete[] copy;
 }

2.使用标准化的字符串类
#include<string>

void userCode(const std::string& s1, const std::string& s2)
{
    std::
string copy = s1;
    
//
    copy += s2;
    
//
}

std::string实现了内存管理
//哪天查看下string的实现

Copyright © 蓝尘