在 c++ 中重载删除运算符
在我的代码中,我重载了 new
和 delete
运算符来获取文件名和行号。在我的代码中,我使用 map
和 stack
。当我从映射中删除特定值时,它只会调用我的重载 delete
函数,但我只希望显式 delete
语句能够访问我的函数,而不是其他函数。我怎样才能做到这一点?
In my code, i have overloaded the new
and delete
operators to get filename and line number. In my code I am using map
and stack
. When i do erase a particular value from the map it just call my overloaded delete
function but I want only explicit delete
statements to be able to access my function, not others. How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想自己的删除来调用您的重载,我不会重载删除运算符,而是创建一个像DeleteMyObject这样的自定义方法,它将调用原始删除,然后创建一个宏来调用此函数并用此宏替换所有删除。
就像
方法可能看起来像这样
你的代码中的
If you only want your own delete to call your overload, I would not overload the delete operator but instead make a custom method like DeleteMyObject which would call the original delete and then create a macro to call this function and replace all your deletes with this macro.
Like
and the method could look like
then in your code
对于大多数“显式”定义而言,
map
和stack
在底层显式调用delete yourObject
,这就是为什么您的删除操作员正在被呼叫。这些删除的合法性并不亚于代码中的删除。顺便问一下,如何获取文件名和行号?请注意,
__FILE__
和__LINE__
可能不起作用。这些将返回文件名和找到它们的行号的行号,这意味着您将获得delete
方法的位置,而不是调用者的位置。 >。为了获得您想要的行为,仅记录“显式”删除并跟踪其位置,您需要用宏调用替换要记录的删除。在这种情况下,您不需要覆盖
delete
。例如:map
andstack
are explicitly callingdelete yourObject
under the hood, for most definitions of "explicit"—that's why your delete operator is getting called. Those deletes are no less legitimate than ones in your code.How do you get the file name and line number, by the way? Beware that
__FILE__
and__LINE__
probably won't work. Those will return the file name and line number of the line number they're found on, meaning you'll get the location of yourdelete
method, not the location of the caller.To get the behavior you want, both only logging "explicit" deletes and tracking their location, you'll need to replace the deletions you want to log with macro calls. In that case you don't need to override
delete
. For example: