STL 关联容器:擦除并取回(不可复制的)元素

STL associative containers: erasing and getting back the (noncopyable) element

本文关键字:可复制 元素 关联 擦除 STL      更新时间:2023-10-16

>我正在使用STL关联容器(std::setstd::map)以及保存std::unique_ptr<>实例的密钥。密钥定义等效于以下内容:

struct Key
{
    std::unique_ptr<Object> object;
    bool operator== (const Key& rhs) const { return object->equal (*rhs.object); }
    bool operator<  (const Key& rhs) const { return object->less (*rhs.object); }
}

众所周知,STL 关联容器(尤其是自 C++11 以来)无法获取对要从中移动的键的非常量引用。而且我的密钥是不可复制的,所以 c++:从容器中删除元素并将其取回不起作用。

有没有非UB方法来克服这个问题?

我目前的解决方案如下:

template <typename T>
using map_pair_type = std::pair<typename T::key_type, typename T::mapped_type>;
template <typename T>
typename T::value_type take_set (T& container, typename T::iterator iterator)
{
    typename T::value_type result = std::move (const_cast<typename T::value_type&> (*iterator));
    container.erase (iterator);
    return result;
}
template <typename T>
map_pair_type<T> take_map (T& container, typename T::iterator iterator)
{
    map_pair_type<T> result {
        std::move (const_cast<typename T::key_type&> (iterator->first)),
        std::move (iterator->second)
    };
    container.erase (iterator);
    return result;
}

这是其中之一:

真的很抱歉。 我们试图完成这项工作,但无法通过 委员会。

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3586.pdf

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3645.pdf

据我所知,您的解决方案与它一样好。 您的地图解决方案确实表现出未定义的行为。 如果第二步引发异常,情况将变得非常糟糕。 除此之外,我怀疑它会起作用。 我怀疑我会因为这么说而投票。

UB 的原因是键被定义为const(而不是仅由常量引用引用)。 在这种情况下抛弃const(并让移动构造函数修改对象)是 UB。

如果N3586被接受,您可以:

move_only_type mot = move(*s.remove(s.begin()));

或:

move_only_key mok = move(m.remove(m.begin())->first);

N3586/N3645在委员会中表现出色。 它经过讨论并通过了工作组阶段,但在全体委员会中被否决。 令人担忧的是,std::lib必须提交UB才能实现它。 它尚未重新提交。

更新

现在可以在 C++17 中执行此操作,但成员函数称为 extract 而不是 remove