gpt4 book ai didi

c++ - 当可移动对象插入 std::set 失败时会发生什么情况?

转载 作者:IT老高 更新时间:2023-10-28 23:17:57 40 4
gpt4 key购买 nike

如果我调用一个可移动的对象会发生什么 std::set<>::insert就可以了,插入不会发生因为已经存在具有相同键的对象集。特别是,以下是否有效:

struct Object
{
std::string key;
// ...

struct OrderByKey
{
bool operator()( Object const& lhs, Object const& rhs) const
{
return lhs.key < rhs.key;
}
};

Object( Object&& other )
: key(std::move(other.key))
// ...
{
}
};

和:

std::set<Object, Object::OrderByKey> registry;
void
register(Object&& o)
{
auto status = registry.insert(std::move(o));
if (!status.second)
throw std::runtime_error("Duplicate entry for " + o.key);
}

registry.insert 之后,当没有插入发生时,有 o是否被移动。 (如果它可能已被移动,我需要事先保存字符串的拷贝,以便在错误信息。 (是的,我知道我总是可以写:

throw std::runtime_error( "Duplicate entry for " + status->first.key );

我可能会这样做。但我还是想知道标准对此有何评论。)

最佳答案

传递给标准库函数的 std::move()ed 对象应被视为已移出:库可以自由地将对象视为其唯一引用,即它即使它不使用它也可能会从它移开。相关条款是 17.6.4.9 [res.on.arguments] 第 2 段,第三个项目符号(在 C++11 和 C++14 中似乎相同):

If a function argument binds to an rvalue reference, the implementation may assume that this parameter is a unique reference to this argument. ...

关于c++ - 当可移动对象插入 std::set 失败时会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25809873/

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