【发布时间】:2016-09-15 13:51:14
【问题描述】:
我知道在 C++ 中编写(动态)插件时,插件分配的内存也应该由插件释放。显然,这同样适用于一般的 DLL。
以下假设:可执行文件、所有插件和所有依赖项(如 Qt)将始终使用相同的编译器构建
由于像QString 这样的类使用浅拷贝等机制,因此使用内部数据指针:
如果插件通过(浅)副本将本地定义的QString 返回到可执行文件,并且副本超出了可执行文件的范围,是否会在错误的进程中释放内存?
示例代码:
// Defined in a DLL which is loaded at runtime
class SamplePlugin : IPlugin
{
public:
QString getSomeStringData() const override
{
return "Hello World"
}
}
// Defined in the executable
void Test( PluginManager* pluginManager )
{
for( auto plugin : pluginManager->loadPlugins() )
{
auto stringData = plugin->getSomeStringData();
doSomethingWith( stringData )
} // stringData goes out of scope here - is this a problem?
}
【问题讨论】:
标签: c++ qt memory-management dll