overload new and delete operators

Expertise: Advanced
Language: C++
April 6, 1999
Overload New and Delete in a Class
It is possible to override the global operators new and delete for a given class. For example, you can use this technique to override the default behavior of operator new in case of a failure. Instead of throwing a std::bad_alloc exception, the class-specific version of new throws a char array:
 
#include <cstdlib> //declarations of malloc and free
#include <new>
#include <iostream>
using namespace std;

class C {
public:
  C();
  void* operator new (size_t size); //implicitly declared as a static member function
  void operator delete (void *p); //implicitly declared as a static member function
};

void* C::operator new (size_t  size) throw (const char *){
  void * p = malloc(size);
  if (p == 0)  throw "allocation failure";  //instead of std::bad_alloc
  return p;
}

void C::operator delete (void *p){ 
  C* pc = static_cast<C*>(p);
  free(p); 
}

int main() {
   C *p = new C; // calls C::new
   delete p;  // calls C::delete
}

Note that the overloaded new and delete implicitly invoke the object's constructor and destructor, respectively. Remember also to define a matching operator delete when you override operator new.
关于原来的new operator如何定义的,我们可以试着参考下面一篇短文来得到一些启示:

An FDIS compliant Operator "new"
Rating: none

Ray Brown (view profile)
February 13, 1999

Microsoft KB article Q167733 points out that Visual C++'s implementation of operator new adopts non-FDIS compliant behavior in that it does not throw an exception in the case of an allocation failure. This may cause problems if not with your own code, then with third-party C++ code that becomes merged into your translation units. Third-party inline and template functions are especially susceptible to malfunction under the non-FDIS compliant semantics. In fact, Microsoft's own STL implementation will fail should new ever return NULL; its allocator does not expect this.

The KB article suggests a workaround that involves calling _set_new_handler. This is a good solution if you link statically with the C/C++ runtime library. But static linking is often an unpopular option among C++ developers on the Win32 platform as it increases module size and can cause a variety of other difficulties (e.g., KB Q126646, Q193462). Calling _set_new_handler from a module which links dynamically with the CRT can cause other difficulties, however, as the new handler is kept in a global variable by the CRT. Different modules in a process might thus attempt to install different new handlers, and failures will result.
(continued)

A naive FDIS compliant implementation of operator new, which might resort to malloc or some other low-level allocation routine, has the disadvantage of changing the behavior of new on the Win32 platform, especially when it comes to diagnostic support in debug mode. Unfortunately, from our own implementation of new we cannot now call CRT's new, since it becomes hidden as the compiler and linker resolve new to our own implementation. In addition, we cannot simply copy the CRT's implementation as it makes use of CRT functions that are not exported.

In what follows we present an implementation of ::operator new that does not suffer from any of the problems outlined above. This solution's key consists of locating CRT's operator new address dynamically, and avoiding the repeated overhead of module search through the use of a static object.

Note that if your module links with MFC, then you should not adopt this solution. MFC provides its own operator new, which throws a CMemoryException* on allocation failure. This is necessary as MFC exception handlers expect all exceptions to be derived from MFC's CException base class. While this has the potential of upsetting third-party code for similar reasons as the FDIS non-compliance mentioned above, such code often works as long as some exception is thrown from new and NULL is never returned. Microsoft's STL appears to fall in this category. Code which expects std::bad_alloc on new failure cannot co-exist peacefully with MFC in a module.


----------
// StdNew.cpp
/*
   Adding this file to a project or, preferred when possible, linking with
   StdNew.obj from a subproject causes the ::operator new
   to assume standard FDIS C++ behavior: the operator will throw
   std::bad_alloc on failure and never return NULL.

   You will not want to link with this file from an MFC project, since the
   MFC library requires that a different exception be thrown on failure and
   arranges for such behavior.

   Note: we choose this approach over setting the new handler, since the new
         handler function is kept in the runtime library on a per-process
         basis. Attempting to control the handler could thus lead to
         contention among dll's that each link dynamically to the runtime
         library.
*/

#include "stdafx.h"

#ifdef _AFX
#error ANSI operator new must not be used in MFC project
#endif

#ifndef _MSC_VER
#error This implementation of ANSI operator new is appropriate for Win32 platforms only
#endif

#ifndef _DLL
#error Project must link dynamically with the C++ runtime library
#endif

class COpNewCrtCacher
{
    COpNewCrtCacher();
    COpNewCrtCacher(const COpNewCrtCacher&);                // not impl
    COpNewCrtCacher& operator = (const COpNewCrtCacher&);   // not impl

public:
    typedef void* (__cdecl *t_OpNewFcn)(size_t);
    static t_OpNewFcn GetCrtOpNew();

private:
    static t_OpNewFcn s_pfCrtOpNew;

    // The following static object ensures that GetCrtOpNew is called during
    // module initialization time and hence threading issues do not arise
    // when multiple threads may call into ::operator new simultaneously
    static COpNewCrtCacher s_GlobalModuleOpNewCrtCacherInitializer;
};

COpNewCrtCacher::COpNewCrtCacher()
{
    // Cached pointer to Crt operator new is set when the static object is
    // constructed or when someone calls ::operator new, whichever comes
    // first. In either case, we avoid threading issues.
    GetCrtOpNew();
}

/*
   This member function along with s_pfCrtOpNew are static so that they can
   continue to be used past the time of destruction of the static object.
*/
COpNewCrtCacher::t_OpNewFcn COpNewCrtCacher::GetCrtOpNew()
{
    if (s_pfCrtOpNew)
        return s_pfCrtOpNew;

    // Name of C++ run time library dll
#   ifdef _DEBUG
    const LPCTSTR sCrtName = _T("MSVCRTD.DLL");
#   else
    const LPCTSTR sCrtName = _T("MSVCRT.DLL");
#   endif

    // Get Crt handle
    HMODULE hCrt = GetModuleHandle(sCrtName);
    _ASSERTE (hCrt);

    // Retrieve function pointer to Crt operator new
    s_pfCrtOpNew = reinterpret_cast <t_OpNewFcn>
                   (GetProcAddress(hCrt, "??2@YAPAXI@Z"));
    _ASSERTE (s_pfCrtOpNew);

    return s_pfCrtOpNew;
}

COpNewCrtCacher::t_OpNewFcn COpNewCrtCacher::s_pfCrtOpNew;
COpNewCrtCacher COpNewCrtCacher::s_GlobalModuleOpNewCrtCacherInitializer;

void* __cdecl operator new(size_t nSize) throw(std::bad_alloc)//~~~~~这个地方是定义方式
{
    // Call the operator new in the Crt
    void* pResult = COpNewCrtCacher::GetCrtOpNew()(nSize);

    // If it returned NULL, throw the exception
    if (! pResult)
        throw std::bad_alloc();

    // Otherwise return pointer to allocated memory
    return pResult;
}

Microsoft KB article Q167733 points out that Visual C++'s implementation of operator new adopts non-FDIS compliant behavior in that it does not throw an exception in the case of an allocation failure. This may cause problems if not with your own code, then with third-party C++ code that becomes merged into your translation units. Third-party inline and template functions are especially susceptible to malfunction under the non-FDIS compliant semantics. In fact, Microsoft's own STL implementation will fail should new ever return NULL; its allocator does not expect this.

The KB article suggests a workaround that involves calling _set_new_handler. This is a good solution if you link statically with the C/C++ runtime library. But static linking is often an unpopular option among C++ developers on the Win32 platform as it increases module size and can cause a variety of other difficulties (e.g., KB Q126646, Q193462). Calling _set_new_handler from a module which links dynamically with the CRT can cause other difficulties, however, as the new handler is kept in a global variable by the CRT. Different modules in a process might thus attempt to install different new handlers, and failures will result.
(continued)

A naive FDIS compliant implementation of operator new, which might resort to malloc or some other low-level allocation routine, has the disadvantage of changing the behavior of new on the Win32 platform, especially when it comes to diagnostic support in debug mode. Unfortunately, from our own implementation of new we cannot now call CRT's new, since it becomes hidden as the compiler and linker resolve new to our own implementation. In addition, we cannot simply copy the CRT's implementation as it makes use of CRT functions that are not exported.

In what follows we present an implementation of ::operator new that does not suffer from any of the problems outlined above. This solution's key consists of locating CRT's operator new address dynamically, and avoiding the repeated overhead of module search through the use of a static object.

Note that if your module links with MFC, then you should not adopt this solution. MFC provides its own operator new, which throws a CMemoryException* on allocation failure. This is necessary as MFC exception handlers expect all exceptions to be derived from MFC's CException base class. While this has the potential of upsetting third-party code for similar reasons as the FDIS non-compliance mentioned above, such code often works as long as some exception is thrown from new and NULL is never returned. Microsoft's STL appears to fall in this category. Code which expects std::bad_alloc on new failure cannot co-exist peacefully with MFC in a module.


----------
// StdNew.cpp
/*
   Adding this file to a project or, preferred when possible, linking with
   StdNew.obj from a subproject causes the ::operator new
   to assume standard FDIS C++ behavior: the operator will throw
   std::bad_alloc on failure and never return NULL.

   You will not want to link with this file from an MFC project, since the
   MFC library requires that a different exception be thrown on failure and
   arranges for such behavior.

   Note: we choose this approach over setting the new handler, since the new
         handler function is kept in the runtime library on a per-process
         basis. Attempting to control the handler could thus lead to
         contention among dll's that each link dynamically to the runtime
         library.
*/

#include "stdafx.h"

#ifdef _AFX
#error ANSI operator new must not be used in MFC project
#endif

#ifndef _MSC_VER
#error This implementation of ANSI operator new is appropriate for Win32 platforms only
#endif

#ifndef _DLL
#error Project must link dynamically with the C++ runtime library
#endif

class COpNewCrtCacher
{
    COpNewCrtCacher();
    COpNewCrtCacher(const COpNewCrtCacher&);                // not impl
    COpNewCrtCacher& operator = (const COpNewCrtCacher&);   // not impl

public:
    typedef void* (__cdecl *t_OpNewFcn)(size_t);
    static t_OpNewFcn GetCrtOpNew();

private:
    static t_OpNewFcn s_pfCrtOpNew;

    // The following static object ensures that GetCrtOpNew is called during
    // module initialization time and hence threading issues do not arise
    // when multiple threads may call into ::operator new simultaneously
    static COpNewCrtCacher s_GlobalModuleOpNewCrtCacherInitializer;
};

COpNewCrtCacher::COpNewCrtCacher()
{
    // Cached pointer to Crt operator new is set when the static object is
    // constructed or when someone calls ::operator new, whichever comes
    // first. In either case, we avoid threading issues.
    GetCrtOpNew();
}

/*
   This member function along with s_pfCrtOpNew are static so that they can
   continue to be used past the time of destruction of the static object.
*/
COpNewCrtCacher::t_OpNewFcn COpNewCrtCacher::GetCrtOpNew()
{
    if (s_pfCrtOpNew)
        return s_pfCrtOpNew;

    // Name of C++ run time library dll
#   ifdef _DEBUG
    const LPCTSTR sCrtName = _T("MSVCRTD.DLL");
#   else
    const LPCTSTR sCrtName = _T("MSVCRT.DLL");
#   endif

    // Get Crt handle
    HMODULE hCrt = GetModuleHandle(sCrtName);
    _ASSERTE (hCrt);

    // Retrieve function pointer to Crt operator new
    s_pfCrtOpNew = reinterpret_cast <t_OpNewFcn>
                   (GetProcAddress(hCrt, "??2@YAPAXI@Z"));
    _ASSERTE (s_pfCrtOpNew);

    return s_pfCrtOpNew;
}

COpNewCrtCacher::t_OpNewFcn COpNewCrtCacher::s_pfCrtOpNew;
COpNewCrtCacher COpNewCrtCacher::s_GlobalModuleOpNewCrtCacherInitializer;

void* __cdecl operator new(size_t nSize) throw(std::bad_alloc)//~~~~~这个地方是定义方式
{
    // Call the operator new in the Crt
    void* pResult = COpNewCrtCacher::GetCrtOpNew()(nSize);

    // If it returned NULL, throw the exception
    if (! pResult)
        throw std::bad_alloc();

    // Otherwise return pointer to allocated memory
    return pResult;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值