bav*_*aza 3 c++ boost boost-multi-index
我有一些复制成本很高的数据类,但必须是可变的,因为它经常根据事件进行更新。我还需要一个多索引容器来容纳许多这样的类。我正在尝试使用 boost::multi_index 进行设置。例如:
struct MutableAndExpensiveToCopy {
int some_value;
std::map<int, std::string> some_huge_map;
std::map<int, std::string> an_even_bigger_map;
}
struct CanBeMultiIndexed
{
// "Payload" - its fields will never be used as indices
MutableAndExpensiveToCopy data;
// Indexes
int id;
std::string label;
}
typedef multi_index_container<
CanBeMultiIndexed,
indexed_by<
ordered_unique<member<CanBeMultiIndexed, int, &CanBeMultiIndexed::id>>,
ordered_non_unique<member<CanBeMultiIndexed,std::string,&CanBeMultiIndexed::label>>
>
> MyDataContainer;
Run Code Online (Sandbox Code Playgroud)
我的问题是 multi_index 将容器中的元素视为常量(为了保持所有索引的完整性)。例如,以下将无法编译:
void main() {
// put some data in the container
MyDataContainer container;
CanBeMultiIndexed e1(1, "one"); // conto'r not shown in class definition for brevity
CanBeMultiIndexed e2(2, "two");
container.insert(e1);
container.insert(e2);
// try to modify data
MyDataContainer::nth_index<1>::type::iterator iter = container.get<1>().find(1);
iter->data.some_value = 5; // constness violation
}
Run Code Online (Sandbox Code Playgroud)
我无法使用该replace()方法,因为复制有效负载类的成本很高。我知道该modify()方法,但使用它似乎很麻烦,因为在我的实际程序中,“有效载荷”类可能包含许多字段,并且为每个字段编写一个函子是不可能的。
有什么建议?
编辑:经过一些玩耍后,我尝试将数据元素替换为 shared_ptr 到MutableAndExpensiveToCopy:
struct CanBeMultiIndexed
{
// "Payload" - its fields will never be used as indices
boost::shared_ptr<MutableAndExpensiveToCopy> data;
// Indexes
int id;
std::string label;
}
Run Code Online (Sandbox Code Playgroud)
这有效,我能够编译我main()的数据修改代码:
void main() {
...
iter->data->some_value = 5; // this works
...
}
Run Code Online (Sandbox Code Playgroud)
这几乎给了我我想要的东西,但我不确定为什么会这样,所以:
->运算符?首先,ImMutableAndExpensiveToCopy似乎恰恰相反 --mutable,因为您试图在示例中更改其内容。试试这个:
struct CanBeMultiIndexed
{
mutable ImMutableAndExpensiveToCopy data;
int id;
std::string label;
}
Run Code Online (Sandbox Code Playgroud)
(并可能更改名称ImMutableAndExpensiveToCopy以保持一致性。)