首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >std::unordered_set<T>::insert(T&&):如果参数存在,是否移动

std::unordered_set<T>::insert(T&&):如果参数存在,是否移动
EN

Stack Overflow用户
提问于 2012-04-06 20:49:32
回答 1查看 874关注 0票数 17

这个问题是关于C++11标准库中几个函数的规范,这些函数将它们的参数作为右值引用,但并不是在所有情况下都使用它们。std::unordered_set<T>::insert(T&&)就是一个例子。

很明显,此方法将使用T的move构造函数在容器中构造元素(如果元素尚不存在)。但是,如果该元素已经存在于容器中,会发生什么呢?我非常确定没有理由改变这种情况下的对象。然而,我在C++11标准中找不到任何支持我的声明的东西。

这里有一个例子来说明为什么这可能很有趣。下面的代码从std::cin中读取行,并删除第一次出现的重复行。

代码语言:javascript
复制
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 << '\n';
    }
}

显然,这个例子适用于GCC 4.7。但我不确定,根据标准,它是否正确。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10043716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档