如何正确替代全球新&删除操作符 [英] How to properly replace global new & delete operators

查看:119
本文介绍了如何正确替代全球新&删除操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,至少有4-5个主题与SO类似的主题。我读了他们每个人,我不觉得他们真的帮助我这个具体问题。如果有人发现重复的问题,我道歉。我在发布之前已经完成了我的搜索,因为它似乎是一个很常见的问题。



我在Windows 7上使用Visual Studio .NET 2003。



我有自己的new / delete重载,指向我自己对malloc()和free()的自定义调用进行诊断。我的新/删除重载是在一个头文件,我已经包含在一些文件。



问题是,代码基本是很多意大利面条,没有简单的方法来确保这些重载被所有的使用。有包括到第三方库是黑盒子。



在我的测试中,我发现STL仍然在调用我自己的新/删除和标准MSVC新/删除调用。 / p>

将我的头文件包含在成千上万个其他文件中似乎不现实,这将花费太长时间。任何人都可以提供一些提示,如何正确和有效地重载新的/删除全局的一切使用我的自定义内存管理器?

解决方案

不是这怎么工作。您更换两个运算符,这是在链接时间完成的。所有你需要做的是写一个单一的TU,定义这些运算符并链接到混合。没有人需要知道这一点:

  // optional_ops.cpp 

void * operator new (std :: size_t n)throw(std :: bad_alloc)
{
// ...
}
void operator delete(void * p)throw $ b {
// ...
}

任何头文件,因为这两个函数的声明已经硬编码到语言中了。


First of all, there were at least 4-5 topics with a similar topic on SO. I read each of them and I don't feel they really help me with this specific issue. If someone else finds a duplicate question I apologize. I've done my share of searching before I posted this, as it seems like a very common question.

I'm using Visual Studio .NET 2003 on Windows 7.

I have my own overloads of new/delete that point to my own custom calls to malloc() and free() for diagnostics. My new/delete overloads are in a header file which I've included in a few files.

The problem is, the code base is pretty much spaghetti and there is no easy way to make sure these overloads get used by everything. There are includes to third party libraries that are black-box. We also use STL everywhere.

In my tests I've found that STL is still mixing calls to my own new/delete and the standard MSVC new/delete calls.

It doesn't seem realistic to include my header file in thousands of other files, that would just take far too long. Can anyone offer some tips on how to properly and effectively overload new/delete globally so everything uses my custom memory manager?

解决方案

That's not how this works. You replace the two operators, and this is done at link time. All you need to do is write a single TU that defines these operators and link it into the mix. Nobody else ever needs to know about this:

// optional_ops.cpp

void * operator new(std::size_t n) throw(std::bad_alloc)
{
  //...
}
void operator delete(void * p) throw()
{
  //...
}

There's no need for any header files, since the declarations of those two functions are already hardcoded into the language, if you will.

这篇关于如何正确替代全球新&删除操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆