gpt4 book ai didi

c++ - 是否有关于诸如 erase/remove_if 之类的算法以及 remove_if 实现的可能副作用的编程标准?

转载 作者:行者123 更新时间:2023-11-30 03:26:25 25 4
gpt4 key购买 nike

我有一个弱指针 vector ,如果指针仍然存在,我想遍历该列表并执行一个函数。如果指针不见了,我想将其移除。

class my_class
{
public:
std::shared_ptr<my_class> pointer_t;
std::weak_ptr<my_class> weak_pointer_t;
...

private:
...
};

class listeners_class
{
public:
typedef std::vector<my_class::weak_ptr> listeners_t;
...

private:
listeners_t f_listeners;
...
};

我注意到我可以直接在 remove_if() 测试函数中实现它,因为 remove_if() 实际上循环遍历整个 vector 并尝试锁定弱 vector 指针已经。另外,这种方式更加原子化

有 lambda 的代码。

    f_listeners.erase(
std::remove_if(
f_listeners.begin()
, f_listeners.end()
, [&ptr](my_class::weak_pointer_t l)
{
my_class::pointer_t ll(l.lock());
if(ll == nullptr)
{
return true;
}
ll->some_callback(ptr); // <<-- side effect!
return false;
})
);

我认为这是不好的做法,但想确认是否有关于此类代码的标准形式。

最佳答案

标准没有指定实现。但是,我们可以从标准中得出,只要您不关心每个元素的预测函数的评估顺序,您的代码就会按预期工作。

首先,[alg.remove]

Effects: Eliminates all the elements referred to by iterator i in the range [first, last) for which the following corresponding conditions hold: *i == value, pred(*i) != false.

...

Complexity: Exactly last - first applications of the corresponding predicate.

这些约束保证预测函数对每个元素恰好执行一次

第二,[res.on.data.races]/8

Unless otherwise specified, C++ standard library functions shall perform all operations solely within the current thread if those operations have effects that are visible to users.

关于the comment in [intro.execution]/11 ,

In other words, function executions do not interleave with each other.

因此您可以考虑在某种意义上执行原子预测函数。

关于c++ - 是否有关于诸如 erase/remove_if 之类的算法以及 remove_if 实现的可能副作用的编程标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48327812/

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