在 c++ 中重载删除运算符

发布于 2024-09-17 20:27:43 字数 224 浏览 5 评论 0原文

在我的代码中,我重载了 newdelete 运算符来获取文件名和行号。在我的代码中,我使用 mapstack。当我从映射中删除特定值时,它只会调用我的重载 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十雾 2024-09-24 20:27:43

如果您只想自己的删除来调用您的重载,我不会重载删除运算符,而是创建一个像DeleteMyObject这样的自定义方法,它将调用原始删除,然后创建一个宏来调用此函数并用此宏替换所有删除。

就像

#define DELETE_MY_OBJECT(obj) DeleteMyObject(obj, __FILE__, __LINE__)

方法可能看起来像这样

void DeleteMyObject(void* obj, char* file, char* line)
{
    // Log delete
    ...

    delete obj;
}

你的代码中的

MyObj* obj = ...
...
DELETE_MY_OBJECT(obj);

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

#define DELETE_MY_OBJECT(obj) DeleteMyObject(obj, __FILE__, __LINE__)

and the method could look like

void DeleteMyObject(void* obj, char* file, char* line)
{
    // Log delete
    ...

    delete obj;
}

then in your code

MyObj* obj = ...
...
DELETE_MY_OBJECT(obj);
桜花祭 2024-09-24 20:27:43

对于大多数“显式”定义而言,mapstack 在底层显式调用 delete yourObject,这就是为什么您的删除操作员正在被呼叫。这些删除的合法性并不亚于代码中的删除。

顺便问一下,如何获取文件名和行号?请注意,__FILE____LINE__ 可能不起作用。这些将返回文件名和找到它们的行号的行号,这意味着您将获得 delete 方法的位置,而不是调用者的位置。 >。

为了获得您想要的行为,仅记录“显式”删除并跟踪其位置,您需要用宏调用替换要记录的删除。在这种情况下,您不需要覆盖 delete。例如:

#define DELETE(p) \
    do { \
        std::cout << __FILE__ << ":" << __LINE__ << ": " << p << std::endl; \
        delete p; \
    }

map and stack are explicitly calling delete 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 your delete 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:

#define DELETE(p) \
    do { \
        std::cout << __FILE__ << ":" << __LINE__ << ": " << p << std::endl; \
        delete p; \
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文