小编Way*_*eng的帖子

std::lock_guard<std::mutex> 和 if constexpr 块的问题

有一个类模板Foo<T>。对于某些特定类型,函数应该使用lock_guard. 这是示例代码:

#include <type_traits>
#include <mutex>
#include <vector>

template<typename T> 
class Foo {
public:
    void do_something(int k) {

        if constexpr(std::is_same_v<T, NeedMutexType>) {
            std::lock_guard<std::mutex> lock(mtx_);
        }

        resource_.push_back(k);
        // code for task with resource_ ...
    }

private:
    std::mutex mtx_;
    std::vector<int> resource_;
};
Run Code Online (Sandbox Code Playgroud)

将会std::lock_guard在 if constexpr 范围的末尾被破坏。(如果不正确,请纠正。)

为了处理这个问题,我可以将下面的任务代码复制resource_到 if constexpr 范围中,或者只使用原始的,std::mutex例如mtx_.lock()& mtx_.unlock()

有什么方法可以处理这个问题std::lock_guard吗?谢谢。

c++ templates mutex lock-guard

6
推荐指数
2
解决办法
249
查看次数

标签 统计

c++ ×1

lock-guard ×1

mutex ×1

templates ×1