C++ 注意事项

1.

 Secrets of Boost Revealed: Checked Delete

http://www.cplusplus.com/forum/articles/44968/

看boost的smart ptr 的实现时,发现

template<class T> void checked_delete(T* p),查了一下:
当对不完整的类(看不到implementation)进行delete操作时,有可能发生undefined行为。
example:
/* Deleter.hpp */

#include<cstdlib>

class A;
class B;
class C;
void func1(A* a);
void func2(B* b);
void func3(C* c);
/* End of Deleter.hpp */


/* Deleter.cpp */
#include "Deleter.hpp"
void func1(A* a)
{
  delete a;
}

void func2(B* b)
{
  delete b;
}

void func3(C* c)
{
  delete c;
}

/* End of Deleter.cpp */

/* Classes.hpp */
class A
{
  private:
    int* x;

  public:
    A(void)
    {
      x = new int(4);
    }

    ~A(void)
    {
      delete x;
    }
};

class B { };

class C
{
  public:
    void operator delete(void* pointer)
    {
      free(pointer);
    }
};
/* End of Classes.hpp */


/* Main.cpp */
#include "Deleter.hpp"
#include "Classes.hpp"
int main(void)
{
  A* a = new A;
  func1(a); // <-- Undefined Behavior - A has a non-trivial destructor
  B* b = new B;
  func2(b); // <-- Legal - B has a trivial destructor and does not overload operator delete
  C* c = new C;
  func3(c); // <-- Undefined Behavior - C has an overloaded operator delete
  return 0;
}
/* End of Main.cpp */

为解决这个问题,boost实现在编译阶段检测(通过sizeof符):
template<class T> void checked_delete(T* p)
{
  typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
  (void) sizeof(type_must_be_complete);
  delete p;
}

template<class T> struct checked_deleter
{
  typedef void result_type;
  typedef T * argument_type;
  void operator()(T * x) const
  {
    boost::checked_delete(x);
  }
};


template<class T> void checked_array_delete(T* p)
{
  typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
  (void) sizeof(type_must_be_complete);
  delete [] p;
}

template<class T> struct checked_array_deleter
{
  typedef void result_type;
  typedef T * argument_type;
  void operator()(T * x) const
  {
      boost::checked_array_delete(x);
  }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值