运算符new和delete重载范围 [英] Operator new and delete overloading scope

查看:126
本文介绍了运算符new和delete重载范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一些有关操作符new和delete的链接和重载的问题.

I stumbled over some questions about linkage and overloading of operator new and delete.

运算符new/delete的全局重载在多大程度上生效

How far does an global overload of operator new/delete take effect

  1. 每个翻译单元
  2. 每个具有至少一个目标文件的链接应用程序会使这些运算符超载

动态链接呢?

这些运算符可以有多个定义吗?如果是哪一个.

Can there be multiple definitions of these operators? If which one is taken.

推荐答案

全局分配和取消分配功能适用于整个应用程序,而不是每个翻译单元.因为它们是全局的,所以除了您认为newnew[]和无限可能的放置位置new的程度是多个定义"之外,不能有多个定义.不幸的是,尤其是在定义自己的全局分配函数时,没有可移植的方法来调用原始全局分配函数.

The global allocation and deallocation functions are for the whole application, not per translation unit. Since they're global there can't be multiple definitions, except to the degree that you consider new, new[] and the infinite number of possible placement new to be "multiple definitions". In particular there is, unfortunately, no portable way to call the original global allocation function when you define your own.

但是,您可以定义特定于类的分配和释放函数.

You can however define class-specific allocation and deallocation functions.

如果要避免在new表达式中使用特定于类的分配函数,可以使用::前缀,即编写::new T,这是调用标准库的放置位置的好主意new.

If you want to avoid picking up a class-specific allocation function in a new-expression you can use a :: prefix, i.e. writing ::new T, and that's a good idea for calling the standard library's placement new.

关于动态链接呢?"目前尚不清楚您的意思. C ++具有静态链接,外部链接和无链接,但没有动态链接.可能您指的是动态库(例如Windows DLL),这是一个非常棘手的问题. C ++标准不直接支持动态库.在实践中,一种安全的方法是不提供您自己的全局分配/取消分配,而是动态链接所有内容(在Windows中,这意味着使用动态链接的运行时库).

Regarding "What about dynamic linkage?" it's unclear what you mean. C++ has static linkage, external linkage and no linkage, but not dynamic linkage. Possibly you're referring to dynamic libraries (like Windows DLLs), and that's a pretty thorny issue. The C++ standard has no direct support for dynamic libraries. One way to be safe in practice is to not provide your own global allocation/deallocation, and to link everything dynamically (in Windows this means using dynamically linked runtime library).

这篇关于运算符new和delete重载范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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