插入值的状态

时间:2019-04-11 11:24:38

标签: c++ containers language-lawyer c++17 move-semantics

如果insert返回false,移动插入后传递给插入的值是否可能保持移出状态?

#include <memory>
#include <map>

#include <cassert>

struct less
{
    template< typename T >
    bool operator () (const std::shared_ptr<T> & lhs, const std::shared_ptr<T> & rhs) const
    {
        return *lhs < *rhs;
    }
};

int main() {
    using key_type = int;
    using value_type = int;
    using map_type = std::map<std::shared_ptr<key_type>, std::shared_ptr<value_type>, less>;
    map_type m;
    auto p = typename map_type::value_type{std::make_shared<key_type>(1), std::make_shared<value_type>(1)};
    if (!m.insert(p).second) {
        assert(false);
    }
    assert(p.first);
    assert(p.second);
    if (m.insert(std::move(p)).second) {
        assert(false);
    }
    assert(p.first);
    assert(p.second);
}

最后两个断言实现的行为是否已定义?

1 个答案:

答案 0 :(得分:3)

std::map::insert的{​​{3}}开始,

template<class P>  
pair<iterator, bool> insert(P&& x);
     

[...]

     

效果:第一种形式等效于return emplace(std::forward<P>(x))

因此它位于[map.modifiers/2]中的std::map::emplace ...中(重点是我):

a_­uniq.​emplace(args)
     

效果:插入且value_­type对象t是由std::forward<​Args​>(​args)...构成的。 t

因此,如果容器中已经存在与等效键相关联的对象,则不会不会进行构建。


让我们使用Llvm实现中的<map>进行验证。在下面的内容中,我删除了部分代码以使其更具可读性。首先,std::map::insert执行此操作:

template <class _Pp, /* some SFINAE... */>
/* symbol visibility ... */
pair<iterator, bool> insert(_Pp&& __p)
    {return __tree_.__insert_unique(_VSTD::forward<_Pp>(__p));}

我们先转到__tree::insert_unique,然后:

pair<iterator, bool> __insert_unique(__container_value_type&& __v) {
    return __emplace_unique_key_args(_NodeTypes::__get_key(__v), _VSTD::move(__v));
}

还不在那里...但是在__tree::emplace_unique_key_args中出现了:

/* Template, template, template... return value... template */
__tree</* ... */>::__emplace_unique_key_args(_Key const& __k, _Args& __args)
{
    __parent_pointer __parent;
    __node_base_pointer& __child = __find_equal(__parent, __k);
    __node_pointer __r = static_cast<__node_pointer>(__child);
    bool __inserted = false;
    if (__child == nullptr)
    {
        /* Some legacy dispatch for C++03... */

        // THIS IS IT:
        __node_holder __h = __construct_node(_VSTD::forward<_Args>(__args)...);
        __insert_node_at(__parent, __child, static_cast<__node_base_pointer>(__h.get()));
        __r = __h.release();
        __inserted = true;
    }
    return pair<iterator, bool>(iterator(__r), __inserted);
}

我认为我们不必研究__find_equal(__parent, __k)就能了解__child == nullptr是触发实际插入的条件。在此分支中,对__construct_node的调用转发了参数,这将窃取您传入的std::shared_ptr<int>管理的资源。另一个分支只需使参数保持不变。< / p>