开自定义operator new与operator delete的迷雾

本文探讨了C++中自定义operatornew和operatordelete的方法及其注意事项,包括如何定义多参数版本及匹配规则,以及在继承体系中的行为表现。
C++里允许用户通过自定义operator new的方式来更改new表达式的行为,这给了程序员定制内存管理方案的自由。但是享受这种自由的时候必须遵守一定的规范,具体可以参见《Effective C++ 2nd》的相关条款。本文补充解释一些特别容易引起误解的问题。 operator new和operator delete都有其正规形式(normal signature): void* operator new(size_t size); void operator delete(void *p); void operator delete(void *p,size_t size); 普通的new与delete表达式在分配与释放内存时调用的就是它们。一般来说operator delete(void*)的优先级比operator delete(void*,size_t)要高,这意味着如果在同一空间(scope)定义了这两种形式的delete,拥有单一参数者优先被编译器选择。这一点在VC7.1中得到验证,不知其它编译器如何? 除了上面的正规形式外,我们还可以定义拥有更多参数的operator new和operator delete,只要保证前者的返回值和第一个参数分别是void*和size_t类型,而后者的分别是void和void*就行了。比如: void* operator new(size_t size,const char* szFile,int nLine); void operator delete(void *p,const char*,int); 表达式new("xxx",20) SomeClass实际上就是告诉编译器调用上面的多参数operator new来分配内存。但是不要依此类推出 delete("xxx",20) pObj,这是非法的。那么怎么才能调用到这个多参数的operator delete呢?实话告诉你,你没有这个权利。呵呵,别吃惊,容我慢慢解释。当两个operator new和operator delete有相等的参数个数,并且除了第一个参数之外其余参数的类型依次完全相同之时,我们称它们为一对匹配的operator new和operator delete。按照这个标准,上面两位就是匹配的一对了。在我们使用 SomeClass *pObj = new("xxx",20) SomeClass 于堆中构建一个对象的过程中,如果在执行SomeClass的构造函数时发生了异常,并且这个异常被捕获了,那么C++的异常处理机制就会自动用与被使用的operator new匹配的operator delete来释放内存(补充一点:在operator new中抛出异常不会导致这样的动作,因为系统认为这标志着内存分配失败)。编译期间编译器按照以下顺序寻找匹配者:首先在被构建对象类的类域中寻找,然后到父类域中,最后到全局域,此过程中一旦找到即停止搜寻并用它来生成正确的内存释放代码,如果没有找到,当发生上述异常情况时将不会有代码用来释放分配的内存,这就造成内存泄漏了。而如果一切正常,delete pObj 则总是会去调用operator delete的正规形式。现在明白了吧,多参数的operator delete不是给我们而是给系统调用的,它平常默默无闻,但在最危急的关头却能挺身而出,保证程序的健壮性。为了有个感性的认识,让我们看看下面的代码(试验环境是VC7.1): #include struct Base { Base() { throw int(3); } ~Base() {} void* operator new( size_t nSize, const char*,int) { void* p = malloc( nSize ); return p; } void operator delete( void *p) { free(p); } void operator delete( void* p,const char*,int) { free( p ); } }; #define NULL 0 #define new new(__FILE__, __LINE__) int main( void ) { Base* p = NULL; try { p = new Base; delete p; } catch(...) { } return 0; } 跟踪执行会发现:程序在 p = new Base 处抛出一个异常后马上跳去执行operator delete(void*,const char*,int)。注释掉Base构造函数中的throw int(3)重来一遍,则new成功,然后执行delete p,这时实际调用的是Base::operator delete(void*)。以上试验结果符合我们的预期。注意,operator new和operator delete是可以被继承和重定义的,那接下来就看看它们在继承体系中的表现。引进一个Base的派生类(代码加在#define NULL 0的前面): struct Son : public Base { Son() { } void* operator new( size_t nSize, const char*,int) { // class Son void* p = malloc( nSize ); return p; } void operator delete( void *p) { // class Son free(p); } void operator delete( void* p,const char*,int) { // class Son free( p ); } }; 然后将main函数中的p = new Base改成p = new Son并且取消对Base()中的throw int(3)的注释,跟踪执行,发现这回new表达式调用的是Son重定义的operator new,抛出异常后也迅速进入了正确的operator delete,即Son重定义的多参数版本。一切都如所料,是吗?呵呵,别急着下结论,让我们把抛异常的语句注释掉再跑一次吧。很明显,有些不对劲。这次delete p没有如我们所愿去调用Son::operator delete(void*),而是找到了在Base中定义的版本。怎么回事?我愿意留一分钟让好奇的你仔细想想。 找到答案了吗?没错,罪魁祸首就是那愚蠢的Base析构函数声明。作为一个领导着派生类的基类,析构函数竟然不声明成virtual函数,这简直就是渎职。赶紧纠正,在~Base()前加上一个神圣的virtual,rebuild and run.....。谢天谢地,世界终于完美了。 可能你会疑惑,在没有给基类析构函数加virtual之前,当发生异常时C++为什么知道正确地调用派生类定义的多参数operator delete,而不是基类的?其实很简单,new一个对象时必须提供此对象的确切类型,所以编译器能够在编译期确定new表达式抛出异常后应该调用哪个类定义的operator delete。对于正常的delete p来说,如果p被声明为非基类类型的指针,编译器就会在编译时决定调用这种声明类型定义的operator delete(静态绑定),而如果p是某种基类类型指针,编译器就会聪明地把到底调用哪个类定义的operator delete留待运行期决定(动态绑定)。那么编译器如何判断p是否是基类指针呢?实际上它的根据就是p的声明类型中定义的析构函数,只有在析构函数是虚拟的情况下p才被看成基类指针。这就可以解释上面碰到的问题。当时p被声明为Base*,程序中它实际指向一个Son对象,但我们并没有把~Base()声明为虚拟的,所以编译器大胆地帮我们做了静态绑定,也即生成调用Base::operator delete(void*)的代码。不过千万不要以为所有编译器都会这样做,以上分析仅仅是基于VC7.1在本次试验中的表现。事实上在C++标准中,经由一个基类指针删除一个派生类对象,而此基类却有一个非虚拟的析构函数,结果未定义。明白了吧老兄,编译器在这种情况下没有生成引爆你电脑的代码已经算是相当客气与负责了。现在你该能够体会Scott Meyers劝你"总是让base class拥有virtual detructor"时的苦心吧。 至于数组版本的operator new[]和opeator delete[],情况一样。朋友们可以自己做试验确认一下。 最后要指出的是,试验代码中对operator new和operator delete的实现相当不规范,负责任的做法仍然请大家参考Scott Meyers的著作。
make -C build 2 ↵ zheng@zheng-Dell-G16-7630 make: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” make[1]: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” make[2]: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” make[2]: 离目录“/home/zheng/test/Alliance-homework/qt-game/build” [ 0%] Built target qt-game_autogen_timestamp_deps make[2]: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” make[2]: 离目录“/home/zheng/test/Alliance-homework/qt-game/build” make[2]: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” [ 16%] Automatic MOC and UIC for target qt-game make[2]: 离目录“/home/zheng/test/Alliance-homework/qt-game/build” [ 16%] Built target qt-game_autogen make[2]: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” make[2]: 离目录“/home/zheng/test/Alliance-homework/qt-game/build” make[2]: 进入目录“/home/zheng/test/Alliance-homework/qt-game/build” [ 33%] Building CXX object CMakeFiles/qt-game.dir/qt-game_autogen/mocs_compilation.cpp.o [ 50%] Building CXX object CMakeFiles/qt-game.dir/main.cpp.o [ 66%] Building CXX object CMakeFiles/qt-game.dir/mainwindow.cpp.o In file included from /usr/include/c++/13/functional:49, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qcomparehelpers.h:27, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qcompare.h:632, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qnamespace.h:13, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qobjectdefs.h:12, from /home/zheng/Qt/6.8.3/gcc_64/include/QtGui/qwindowdefs.h:8, from /home/zheng/Qt/6.8.3/gcc_64/include/QtWidgets/qwidget.h:8, from /home/zheng/Qt/6.8.3/gcc_64/include/QtWidgets/qmainwindow.h:8, from /home/zheng/Qt/6.8.3/gcc_64/include/QtWidgets/QMainWindow:1, from /home/zheng/test/Alliance-homework/qt-game/mainwindow.h:4, from /home/zheng/test/Alliance-homework/qt-game/mainwindow.cpp:1: /usr/include/c++/13/bits/stl_function.h: In instantiation of ‘constexpr bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = QPoint]’: /usr/include/c++/13/bits/stl_tree.h:2534:33: required from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::find(const _Key&) [with _Key = QPoint; _Val = std::pair<const QPoint, QGraphicsRectItem*>; _KeyOfValue = std::_Select1st<std::pair<const QPoint, QGraphicsRectItem*> >; _Compare = std::less<QPoint>; _Alloc = std::allocator<std::pair<const QPoint, QGraphicsRectItem*> >; iterator = std::_Rb_tree<QPoint, std::pair<const QPoint, QGraphicsRectItem*>, std::_Select1st<std::pair<const QPoint, QGraphicsRectItem*> >, std::less<QPoint>, std::allocator<std::pair<const QPoint, QGraphicsRectItem*> > >::iterator]’ /usr/include/c++/13/bits/stl_map.h:1220:25: required from ‘std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::find(const key_type&) [with _Key = QPoint; _Tp = QGraphicsRectItem*; _Compare = std::less<QPoint>; _Alloc = std::allocator<std::pair<const QPoint, QGraphicsRectItem*> >; iterator = std::_Rb_tree<QPoint, std::pair<const QPoint, QGraphicsRectItem*>, std::_Select1st<std::pair<const QPoint, QGraphicsRectItem*> >, std::less<QPoint>, std::allocator<std::pair<const QPoint, QGraphicsRectItem*> > >::iterator; key_type = QPoint]’ /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qmap.h:373:27: required from ‘T& QMap<Key, T>::operator[](const Key&) [with Key = QPoint; T = QGraphicsRectItem*]’ /home/zheng/test/Alliance-homework/qt-game/mainwindow.cpp:280:24: required from here /usr/include/c++/13/bits/stl_function.h:408:20: error: no match for ‘operator<’ (operand types are ‘const QPoint’ and ‘const QPoint’) 408 | { return __x < __y; } | ~~~~^~~~~ In file included from /usr/include/c++/13/utility:69, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qglobal.h:15, from /home/zheng/Qt/6.8.3/gcc_64/include/QtGui/qtguiglobal.h:7, from /home/zheng/Qt/6.8.3/gcc_64/include/QtWidgets/qtwidgetsglobal.h:7, from /home/zheng/Qt/6.8.3/gcc_64/include/QtWidgets/qmainwindow.h:7: /usr/include/c++/13/bits/stl_pair.h:835:5: note: candidate: ‘template<class _T1, class _T2> constexpr bool std::operator<(const pair<_T1, _T2>&, const pair<_T1, _T2>&)’ 835 | operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y) | ^~~~~~~~ /usr/include/c++/13/bits/stl_pair.h:835:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::pair<_T1, _T2>’ 408 | { return __x < __y; } | ~~~~^~~~~ In file included from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qttypetraits.h:10, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qforeach.h:11, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qglobal.h:57: /usr/include/c++/13/optional:1254:5: note: candidate: ‘template<class _Tp, class _Up> constexpr std::__optional_lt_t<_Tp, _Up> std::operator<(const optional<_Tp>&, const optional<_Up>&)’ 1254 | operator<(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) | ^~~~~~~~ /usr/include/c++/13/optional:1254:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::optional<_Tp>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/optional:1322:5: note: candidate: ‘template<class _Tp> constexpr bool std::operator<(const optional<_Tp>&, nullopt_t)’ 1322 | operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept | ^~~~~~~~ /usr/include/c++/13/optional:1322:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::optional<_Tp>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/optional:1327:5: note: candidate: ‘template<class _Tp> constexpr bool std::operator<(nullopt_t, const optional<_Tp>&)’ 1327 | operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept | ^~~~~~~~ /usr/include/c++/13/optional:1327:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::optional<_Tp>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/optional:1388:5: note: candidate: ‘template<class _Tp, class _Up> constexpr std::__optional_lt_t<_Tp, _Up> std::operator<(const optional<_Tp>&, const _Up&)’ 1388 | operator<(const optional<_Tp>& __lhs, const _Up& __rhs) | ^~~~~~~~ /usr/include/c++/13/optional:1388:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::optional<_Tp>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/optional:1394:5: note: candidate: ‘template<class _Tp, class _Up> constexpr std::__optional_lt_t<_Up, _Tp> std::operator<(const _Up&, const optional<_Tp>&)’ 1394 | operator<(const _Up& __lhs, const optional<_Tp>& __rhs) | ^~~~~~~~ /usr/include/c++/13/optional:1394:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::optional<_Tp>’ 408 | { return __x < __y; } | ~~~~^~~~~ In file included from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qttypetraits.h:11: /usr/include/c++/13/tuple:1961:5: note: candidate: ‘template<class ... _TElements, class ... _UElements> constexpr bool std::operator<(const tuple<_UTypes ...>&, const tuple<_UTypes ...>&)’ 1961 | operator<(const tuple<_TElements...>& __t, | ^~~~~~~~ /usr/include/c++/13/tuple:1961:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::tuple<_UTypes ...>’ 408 | { return __x < __y; } | ~~~~^~~~~ In file included from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qttypetraits.h:14: /usr/include/c++/13/variant:1264:3: note: candidate: ‘template<class ... _Types> constexpr bool std::operator<(const variant<_Types ...>&, const variant<_Types ...>&)’ 1264 | _VARIANT_RELATION_FUNCTION_TEMPLATE(<, less) | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/include/c++/13/variant:1264:3: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::variant<_Types ...>’ 408 | { return __x < __y; } | ~~~~^~~~~ In file included from /usr/include/c++/13/bits/stl_algobase.h:67, from /usr/include/c++/13/bits/specfun.h:43, from /usr/include/c++/13/cmath:3699, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qnumeric.h:15, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qglobal.h:62: /usr/include/c++/13/bits/stl_iterator.h:455:5: note: candidate: ‘template<class _Iterator> constexpr bool std::operator<(const reverse_iterator<_Iterator>&, const reverse_iterator<_Iterator>&)’ 455 | operator<(const reverse_iterator<_Iterator>& __x, | ^~~~~~~~ /usr/include/c++/13/bits/stl_iterator.h:455:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::reverse_iterator<_Iterator>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/bits/stl_iterator.h:500:5: note: candidate: ‘template<class _IteratorL, class _IteratorR> constexpr bool std::operator<(const reverse_iterator<_Iterator>&, const reverse_iterator<_IteratorR>&)’ 500 | operator<(const reverse_iterator<_IteratorL>& __x, | ^~~~~~~~ /usr/include/c++/13/bits/stl_iterator.h:500:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::reverse_iterator<_Iterator>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/bits/stl_iterator.h:1705:5: note: candidate: ‘template<class _IteratorL, class _IteratorR> constexpr bool std::operator<(const move_iterator<_IteratorL>&, const move_iterator<_IteratorR>&)’ 1705 | operator<(const move_iterator<_IteratorL>& __x, | ^~~~~~~~ /usr/include/c++/13/bits/stl_iterator.h:1705:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::move_iterator<_IteratorL>’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/bits/stl_iterator.h:1770:5: note: candidate: ‘template<class _Iterator> constexpr bool std::operator<(const move_iterator<_IteratorL>&, const move_iterator<_IteratorL>&)’ 1770 | operator<(const move_iterator<_Iterator>& __x, | ^~~~~~~~ /usr/include/c++/13/bits/stl_iterator.h:1770:5: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const std::move_iterator<_IteratorL>’ 408 | { return __x < __y; } | ~~~~^~~~~ In file included from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer.h:12, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qdebug.h:18, from /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qvariant.h:12, from /home/zheng/Qt/6.8.3/gcc_64/include/QtGui/qaction.h:13, from /home/zheng/Qt/6.8.3/gcc_64/include/QtWidgets/qwidget.h:12: /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer_impl.h:816:24: note: candidate: ‘template<class T, class X> bool operator<(const QSharedPointer<T>&, const QSharedPointer<T>&)’ 816 | Q_INLINE_TEMPLATE bool operator<(const QSharedPointer<T> &ptr1, const QSharedPointer<X> &ptr2) | ^~~~~~~~ /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer_impl.h:816:24: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const QSharedPointer<T>’ 408 | { return __x < __y; } | ~~~~^~~~~ /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer_impl.h:822:24: note: candidate: ‘template<class T, class X> bool operator<(const QSharedPointer<T>&, X*)’ 822 | Q_INLINE_TEMPLATE bool operator<(const QSharedPointer<T> &ptr1, X *ptr2) | ^~~~~~~~ /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer_impl.h:822:24: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: ‘const QPoint’ is not derived from ‘const QSharedPointer<T>’ 408 | { return __x < __y; } | ~~~~^~~~~ /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer_impl.h:828:24: note: candidate: ‘template<class T, class X> bool operator<(T*, const QSharedPointer<T>&)’ 828 | Q_INLINE_TEMPLATE bool operator<(T *ptr1, const QSharedPointer<X> &ptr2) | ^~~~~~~~ /home/zheng/Qt/6.8.3/gcc_64/include/QtCore/qsharedpointer_impl.h:828:24: note: template argument deduction/substitution failed: /usr/include/c++/13/bits/stl_function.h:408:20: note: mismatched types ‘T*’ and ‘QPoint’ 408 | { return __x < __y; } | ~~~~^~~~~ /usr/include/c++/13/variant:1306:18: note: candidate: ‘constexpr bool std::operator<(monostate, monostate)’ 1306 | constexpr bool operator<(monostate, monostate) noexcept { return false; } | ^~~~~~~~ /usr/include/c++/13/variant:1306:28: note: no known conversion for argument 1 from ‘const QPoint’ to ‘std::monostate’ 1306 | constexpr bool operator<(monostate, monostate) noexcept { return false; } | ^~~~~~~~~ make[2]: *** [CMakeFiles/qt-game.dir/build.make:111:CMakeFiles/qt-game.dir/mainwindow.cpp.o] 错误 1 make[2]: 离目录“/home/zheng/test/Alliance-homework/qt-game/build” make[1]: *** [CMakeFiles/Makefile2:86:CMakeFiles/qt-game.dir/all] 错误 2 make[1]: 离目录“/home/zheng/test/Alliance-homework/qt-game/build” make: *** [Makefile:136:all] 错误 2 make: 离目录“/home/zheng/test/Alliance-homework/qt-game/build”
最新发布
10-05
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值