This question is about the specification of several functions in the C++11 Standard Library, that take their arguments as rvalue references, but do not consume them in all cases. One example is
std::unordered_set<T>::insert(T&&)
.
It is pretty clear, that this method will use the move constructor of T
to construct the element within the container, if it does not already exist. However, what happens if the element already exists in the container? I am pretty sure there is no reason the change the object in the case. However, I didn t find anything in the C++11 Standard supporting my claim.
这里是一个例子,可以说明为什么这一点可能令人感兴趣。 下面的法典中行文如下:混淆并删除重复线的首次出现。
std::unordered_set<std::string> seen;
std::string line;
while (getline(std::cin, line)) {
bool inserted = seen.insert(std::move(line)).second;
if (!inserted) {
/* Is it safe to use line here, i.e. can I assume that the
* insert operation hasn t changed the string object, because
* the string already exists, so there is no need to consume it. */
std::cout << line <<
;
}
}
Apparently, this example works with GCC 4.7. But I am not sure, if it is correct according to the standard.