相关疑难解决方法(0)

map move-insertion是否保证元素是否被移动?

C++中的标准"map"容器允许您插入rvalue:

T x;

std::map<int, T> m;

// m[1];  // populate "1"

auto it = m.insert(std::make_pair(1, std::move(x)));
Run Code Online (Sandbox Code Playgroud)

问题是当元素已经存在时会发生什么,即it->second == false.该元素是否x已被"移出"?例如,如果它是一个唯一的指针,将x被重置为null?

在上述情况下,答案似乎是"是",因为移动发生在创建该对时已经发生.但是现在假设我想更新现有值,但仍然保留值是否已经存在的信息(所以我不能说m[1] = std::move(x);).在这种情况下,是否有可能"不要离开"物体?

我在GCC发现了以下工作[更新:作品GCC 4.6,并没有工作在GCC 4.8:

auto it = m.insert(std::pair<const int, T &&>(1, std::move(x)));
Run Code Online (Sandbox Code Playgroud)

但这是否保证不动?

c++ move-semantics c++11

11
推荐指数
1
解决办法
624
查看次数

标签 统计

c++ ×1

c++11 ×1

move-semantics ×1