gpt4 book ai didi

C++动态加载类: Why is a "destroy" function needed?

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:40 25 4
gpt4 key购买 nike

This page检查并给出了一个非常清晰的示例,说明如何动态加载和使用类,但有些东西我很难理解:

我明白为什么需要“创建”功能,但为什么需要“销毁”功能?为什么不将接口(interface)析构函数声明为纯虚拟的就足够了?

我做了一个相同的例子,除了:

~polygon() = 0;

triangle 的析构函数是:

triangle::~triangle() {
std::cout << "triangle Dtor is called" <<std::endl;
}

然后当我使用:

delete poly;

确实显示了消息(Linux 下的 GCC 5.4.0)。

我试图寻找其他示例,但他们都提到并使用了“销毁”功能,没有使用简单的纯虚拟析构函数的示例,这让人相信我在这里遗漏了一些东西,所以..它是什么?

不想使用 destroy 函数的背景是我想在 shared_ptr 中使用分配的对象并且以后不关心它的生命周期,使用“destroy”函数会很棘手,因此我需要知道是否有必要。

最佳答案

the same link 中进一步阅读:

You must provide both a creation and a destruction function; you must not destroy the instances using delete from inside the executable, but always pass it back to the module. This is due to the fact that in C++ the operators new and delete may be overloaded; this would cause a non-matching new and delete to be called, which could cause anything from nothing to memory leaks and segmentation faults. The same is true if different standard libraries are used to link the module and the executable.

此处的关键字是 new 和 delete 可能会被重载,因此如果您使用 delete,则在调用者的代码中执行的操作与在共享对象的代码中执行的操作不同> 从二进制文件内部调用析构函数,并根据共享对象中的析构函数释放内存,但这可能不是共享对象中 delete 运算符的行为,可能是 new共享对象没有分配任何内存,因此您可能会遇到段错误,也许 new 正在做的事情不仅仅是为该对象分配内存并且不调用匹配的 delete 共享对象中存在泄漏,共享对象和二进制文件之间也可能存在不同的堆处理。

在任何情况下,shared_ptr 都可以通过调用自定义删除器的 lambda 函数相当轻松地获得自定义删除器;是的,shared_ptr 不能在其模板参数中包含删除器,这有点烦人,但您可以编写一个简单的包装器,使其更简单/更简洁,以在所有位置使用一致的删除器创建它(目前没有可用的编译器,请原谅任何拼写错误):

shared_ptr<triangle> make_shared_triangle(triangle *t) {
return std::shared_ptr<triangle>(t, [](triangle *t) { destroy_triangle(t); });
}

关于C++动态加载类: Why is a "destroy" function needed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40109135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com