勤能补拙,Expter

成都游戏Coder,记录游戏开发过程的笔记和心得!

一些代码总结(特化类的友元模板重载,常见内存泄漏)

A.特化类的友元模板函数的操作符重载

最近写一测试代码关于特化类的友元模板函数的操作符重载遇到一问题。
先贴一个错误代码:
 1#pragma region 类DTest信息
 2
 3// 声明一个类
 4template<class Type , int dim>
 5class DTest
 6{
 7public:
 8    // 构造函数
 9    DTest()
10    {
11        memset(_cords,0,sizeof(_cords));
12    }

13    DTest(Type cord[dim])
14    {
15        memcpy(_cords,cord,sizeof(cord));
16    }

17
18    // 友元模板
19    friend ostream & operator << (ostream & out , const DTest<Type,dim> & data);
20
21private:
22  Type _cords[dim];
23}
;
24// 友元模板的实现
25template<class Type, int dim>
26ostream & operator << (ostream & out , const DTest<Type,dim> & data)
27{
28    for(int i = 0 ; i < dim-1 ; i++)
29        out << data._cords[i] <<" ";
30
31    out <<endl;
32    return out;
33}

34
35#pragma endregion


用devc++,Vs2005,vc2008都不能编译通过,报连接错误,或者报模板函数是一个普通非模板类,或者非模板函数。

于是翻开C++  Primer,在16.4节有详细的说明,
1.对于一个特化的类,声明一个友元模板必须对友元模板授予类的一个实例。
2.对特定实例化的友元关系时,必须在可以用于友元声明之前声明类或函数。

所以下面是修改后的代码

 1template<class Type , int dim>
 2class DTest;
 3template<class Type , int dim>
 4ostream & operator << (ostream &out ,const DTest<Type,dim> &sess);
 5
 6
 7#pragma region 类DTest信息
 8template<class Type , int dim>
 9class DTest
10{
11public:
12        // 构造函数
13    DTest()
14    {
15        memset(_cords,0,sizeof(_cords));
16    }

17    DTest(Type cord[dim])
18    {
19        memcpy(_cords,cord,sizeof(cord));
20    }

21
22        // 特化时,<Type,dim> 省略为<>
23    friend ostream & operator << <>(ostream & out , const DTest<Type,dim> & data);
24
25private:
26  Type _cords[dim];
27}
;
28
29// 友元模板的实现
30template<class Type, int dim>
31ostream & operator << (ostream & out , const DTest<Type,dim> & data)
32{
33    for(int i = 0 ; i < dim-1 ; i++)
34        out << data._cords[i] <<" ";
35
36    out <<endl;
37    return out;
38}

39#pragma endregion

 



B. 常见的几种内存泄漏
  1.分配空间未释放
  2.嵌套对象指针未释放,
       比如,一个类中包含另一个类的指针,在初始化的时候分配空间,缺没有在析构函数释放他。
  3.释放一个对象数组的时候没有使用[] ,
       delete m_pObj; 只是释放第一个&m_pObj[0] 对象,应该使用delete [] m_pObj;
  4.出现浅拷贝现象
  5.返回一个动态分配的对象,其实可以看【effective c++】 的条款23: 必须返回一个对象时不要试图返回一个引用
    

先总结这些,以后慢慢记录我的学习笔记。


     

 

posted on 2009-04-22 22:21 expter 阅读(694) 评论(0)  编辑 收藏 引用 所属分类: 其他学习笔记工作笔记算法与数据结构


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理