winapi - 临界区对象可以存储在 std::vector 中吗?

标签 winapi move stdvector critical-section

根据the documentation ,关键部分对象无法复制或 move 。

这是否意味着它不能作为实例安全地存储在 std::vector 样式集合中?

最佳答案

正确; CRITICAL_SECTION不应复制/move 对象,因为它可能会停止工作(例如,它可能包含指向自身的指针)。

一种方法是存储智能指针向量,例如(C++17 代码):

#include <windows.h>
#include <memory>
#include <vector>

using CS_ptr = std::unique_ptr<CRITICAL_SECTION, decltype(&DeleteCriticalSection)>;

CS_ptr make_CriticalSection(void)
{
    CS_ptr p(new CRITICAL_SECTION, DeleteCriticalSection);
    InitializeCriticalSection(p.get());
    return p;
}

int main()
{
    std::vector<CS_ptr> vec;
    vec.push_back( make_CriticalSection() );    
}
<小时/>

考虑使用std::recursive_mutex它是 CRITICAL SECTION 的直接替代品(可能只是将其包装在 Windows 实现中),并在其析构函数中执行正确的初始化和释放。

标准互斥锁也是不可复制的,因此在这种情况下您可以使用 std::unique_ptr<std::recursive_mutex>如果你想要它们的向量。

As discussed here还要考虑您是否真的想要 std::mutex而不是递归互斥锁。

注意:Windows Mutex是一个进程间对象; std::mutex和好友对应的是CRITICAL_SECTION .

<小时/>

我还建议重新考虑对互斥向量的需求;无论您尝试做什么,都可能有更好的解决方案。

关于winapi - 临界区对象可以存储在 std::vector 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534212/

相关文章:

python - Windows 与 Python Hook

c++ - 使用 vector 在初始化列表中 move 构造函数

swift - 在 SpriteKit 中使用滑动识别器

c++ - 我可以有一个与另一个 vector 共享存储空间的 vector 吗?

c++ - JRTPLIB/header include问题

c++ - 创建只能由 Windows 服务打开的文件

c - 如何使用 MinGW 创建微型 PE (Win32) 可执行文件

linux - 在 Linux 中使用符号链接(symbolic link)将文件从一个位置 move 到另一个位置

c++ - 如何在文件中节省空间地存储和检索 std::vector<int> 值

C++ std::vector::clear() 崩溃