要插入的值的状态

问题描述 投票:3回答:1

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

#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);
}

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

c++ containers language-lawyer c++17 move-semantics
1个回答
3
投票

来自[map.modifiers/2]std::map::insert,我们有

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

[...]

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

所以它来自std::map::emplace ......来自[associative.reqmts/8](强调我的):

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>管理的资源。另一个分支只是让参数不受影响。

© www.soinside.com 2019 - 2024. All rights reserved.