gpt4 book ai didi

c++ - std::unordered_set::insert(T&&): 如果存在则移动参数

转载 作者:IT老高 更新时间:2023-10-28 22:22:03 29 4
gpt4 key购买 nike

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

很明显,这个方法将使用 T 的移动构造函数构造容器中的元素,如果它不存在的话。但是,如果元素已经存在于容器中会怎样?我很确定没有理由更改案例中的对象。但是,我没有在 C++11 标准中找到任何支持我的主张的内容。

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

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。但我不确定,如果按照标准是正确的。

最佳答案

我在标准(17.4.6.9)中找到了这个注释:

[ Note: If a program casts an lvalue to an xvalue while passing that lvalue to a library function (e.g. by calling the function with the argument move(x)), the program is effectively asking that function to treat that lvalue as a temporary. The implementation is free to optimize away aliasing checks which might be needed if the argument was an lvalue. — end note ]

虽然它没有直接回答您的问题,但它确实表明您已经有效地将库函数的参数“赋予”为临时的,因此一旦您调用 insert,我就不会依赖它的值。据我所知,库实现将有权从参数中移动,即使它随后确定它不会将值保留在容器中。

关于c++ - std::unordered_set<T>::insert(T&&): 如果存在则移动参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10043716/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com