不。
虽然@NathanOliver指出当且仅当没有等效键时才会插入元素,但它不能保证不会修改参数。
实际上,[map.modifiers] 是这样说的
template <class P>
pair<iterator, bool> insert(P&& x);
相当于return emplace(std::forward<P>(x)).
Whereemplace
可以完美地转发参数以构造另一个P
,x
处于某种有效但不确定的状态。
这是一个示例,它还演示(不证明)使用std::map
(关联容器),值会移动一点:
#include <iostream>
#include <utility>
#include <string>
#include <map>
struct my_class
{
my_class() = default;
my_class(my_class&& other)
{
std::cout << "move constructing my_class\n";
val = other.val;
}
my_class(const my_class& other)
{
std::cout << "copy constructing my_class\n";
val = other.val;
}
my_class& operator=(const my_class& other)
{
std::cout << "copy assigning my_class\n";
val = other.val;
return *this;
}
my_class& operator=(my_class& other)
{
std::cout << "move assigning my_class\n";
val = other.val;
return *this;
}
bool operator<(const my_class& other) const
{
return val < other.val;
}
int val = 0;
};
int main()
{
std::map<my_class, int> my_map;
my_class a;
my_map[a] = 1;
std::pair<my_class, int> b = std::make_pair(my_class{}, 2);
my_map.insert(std::move(b)); // will print that the move ctor was called
}