【发布时间】:2012-01-26 15:09:12
【问题描述】:
我想知道如何创建像std::map<T1, T2>(T1allocator, T2allocator, T1deallocator, T2deallocator) 这样的东西,这样当任何人尝试从任何堆中将键值对插入我的地图或修改某些数据时,将在原始地图创建者堆中创建数据而不是在其他尝试将自己的数据传递给它的堆中?
假设我们有一个 DLL 库(在 Windows 上)并且我们动态地(在运行时)将它附加到我们的主应用程序。该库(作为主应用程序)是使用静态运行时编译的。因此可能会获得 2 个不同的 STL 和 2 个不同的堆 - 一个带有 DLL,一个带有 App。
现在假设我们希望我们的插件/dll 仅使用主应用程序堆中的内存。
让我们来看一些简单的演示代码。
我们创建了一个简单的插件界面,我们的主应用程序都知道:
class plugin:
{
public:
virtual void pass_and_modify_data( boost::shared_ptr<std::map<std::string, std::string> > a) =0;
};
我们使用以下方法创建了 pugin DLL:
#include "plug_in_interface.h"
class my_plugin: public plugin
{
public:
virtual void pass_and_modify_data( boost::shared_ptr<std::map<std::string, std::string> > a)
{
a->insert(std::pair<std::string, std::string>("hello", "World"));
(*a)["world"] = "hello";
}
};
现在我们想将地图从我们的应用程序传递给插件,但将所有传递给我们地图的值分配到主应用程序堆上。
如何做这样的事情 - 如何让std::map 将给定的键和值重新分配到主应用程序哈希中,而插件代码开发人员不会注意到? (这里注意我的意思是像使用自定义释放器放入地图字符串或编写任何特殊的非平凡代码)
查看sehe's我要创建的答案和演示:
如果我把它写出来,我的主要内容会是这样的:
#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/flyweight.hpp>
#include "plug_in_interface.h"
using namespace boost;
using namespace boost::flyweights;
typedef flyweight<
std::string,
hashed_factory<
boost::hash<std::string>,
std::equal_to<key_value>,
std::allocator<boost::mpl::_1> // here we get errors like C2065: 'key_value' : undeclared identifier
>
> customString;
int main()
{
// boring part - load plugin... into something like boost::shared_ptr<plugin> my_plugin
//intresting part - create map in main heap and make all its values and keys be forced to be allocated or reallocated in main heap
std::cout << std::endl << "Map allocator mased memory management:" << std::endl;
std::cin.get();
{
boost::shared_ptr<std::map<std::string, std::string> > a (new std::map<customString, customString>());
my_plugin->pass_and_modify_data(a);
std::cout << "modified data: " << (*a)["hello"] << (*a)["world"] << std::endl;
}
std::cout << "removed data" << std::endl;
std::cin.get();
}
由于 customString 类型的定义方式,目前我无法编译这个东西。编译器显示大量编译器错误。如何使类型 def 更正确?
一般来说,我对 stl::allocators 完全没问题,我真正需要的只是分配器与堆的绑定方式(就像我们可以使用 shared_ptrs 一样),这可能吗?
【问题讨论】:
-
您是否考虑过只是不这样做? (不要将共享库静态链接到它的运行时......)。此外,如果您在主程序中构建映射并传递它,分配器也会被复制。
-
@sehe:为什么我需要将共享库静态链接到它的运行时这样丑陋的东西 - 使最终用户无需安装任何运行时=)我的主应用程序也是静态编译的,什么插件会被动态编译吗?
-
这是一个逆转。如果您希望事物动态链接,那么动态加载有什么意义?还有,你问这个问题干嘛?你有你的理由。考虑到这一点,您可能最好在不使用动态链接但使用纯 C 插件接口(使用 HANDLE 习惯用法)的情况下最好解决此问题或使用 COM 进行接口,这正是为此Windows 上的用途
标签: c++ memory-management boost stl map