xref: /third_party/lzma/CPP/Common/NewHandler.h (revision 370b324c)
1// Common/NewHandler.h
2
3#ifndef ZIP7_INC_COMMON_NEW_HANDLER_H
4#define ZIP7_INC_COMMON_NEW_HANDLER_H
5
6/*
7NewHandler.h and NewHandler.cpp allows to solve problem with compilers that
8don't throw exception in operator new().
9
10This file must be included before any code that uses operators new() or delete()
11and you must compile and link "NewHandler.cpp", if you use some old MSVC compiler.
12
13DOCs:
14  Since ISO C++98, operator new throws std::bad_alloc when memory allocation fails.
15  MSVC 6.0 returned a null pointer on an allocation failure.
16  Beginning in VS2002, operator new conforms to the standard and throws on failure.
17
18  By default, the compiler also generates defensive null checks to prevent
19  these older-style allocators from causing an immediate crash on failure.
20  The /Zc:throwingNew option tells the compiler to leave out these null checks,
21  on the assumption that all linked memory allocators conform to the standard.
22
23The operator new() in some MSVC versions doesn't throw exception std::bad_alloc.
24MSVC 6.0 (_MSC_VER == 1200) doesn't throw exception.
25The code produced by some another MSVC compilers also can be linked
26to library that doesn't throw exception.
27We suppose that code compiled with VS2015+ (_MSC_VER >= 1900) throws exception std::bad_alloc.
28For older _MSC_VER versions we redefine operator new() and operator delete().
29Our version of operator new() throws CNewException() exception on failure.
30
31It's still allowed to use redefined version of operator new() from "NewHandler.cpp"
32with any compiler. 7-Zip's code can work with std::bad_alloc and CNewException() exceptions.
33But if you use some additional code (outside of 7-Zip's code), you must check
34that redefined version of operator new() is not problem for your code.
35*/
36
37#include <stddef.h>
38
39#ifdef _WIN32
40// We can compile my_new and my_delete with _fastcall
41/*
42void * my_new(size_t size);
43void my_delete(void *p) throw();
44// void * my_Realloc(void *p, size_t newSize, size_t oldSize);
45*/
46#endif
47
48
49#if defined(_MSC_VER) && (_MSC_VER < 1600)
50  // If you want to use default operator new(), you can disable the following line
51  #define Z7_REDEFINE_OPERATOR_NEW
52#endif
53
54
55#ifdef Z7_REDEFINE_OPERATOR_NEW
56
57// std::bad_alloc can require additional DLL dependency.
58// So we don't define CNewException as std::bad_alloc here.
59
60class CNewException {};
61
62void *
63#ifdef _MSC_VER
64__cdecl
65#endif
66operator new(size_t size);
67
68void
69#ifdef _MSC_VER
70__cdecl
71#endif
72operator delete(void *p) throw();
73
74#else
75
76#include <new>
77
78#define CNewException std::bad_alloc
79
80#endif
81
82/*
83#ifdef _WIN32
84void *
85#ifdef _MSC_VER
86__cdecl
87#endif
88operator new[](size_t size);
89
90void
91#ifdef _MSC_VER
92__cdecl
93#endif
94operator delete[](void *p) throw();
95#endif
96*/
97
98#endif
99