Created
May 14, 2023 10:58
-
-
Save eliemichel/2e154152f981e3f16827ba4d17d1123a to your computer and use it in GitHub Desktop.
An example of RAII wrapper for WebGPU's wgpu::Buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using https://github.com/eliemichel/WebGPU-Cpp | |
#include <webgpu/webgpu.hpp> | |
namespace raii { | |
class Buffer { | |
public: | |
// Whenever a RAII instance is created, we create an underlying resource | |
Buffer(wgpu::Device device, const wgpu::BufferDescriptor& bufferDesc) | |
: m_raw(device.createBuffer(bufferDesc)) | |
{} | |
// We define a destructor... | |
~Buffer() { | |
if (!m_raw) return; | |
m_raw.destroy(); | |
wgpuBufferRelease(m_raw); | |
} | |
// Delete copy semantics | |
Buffer& operator=(const Buffer& other) = delete; | |
Buffer(const Buffer& other) = delete; | |
Buffer&& operator=(Buffer&& other) { | |
m_raw = other.m_raw; | |
other.m_raw = nullptr; | |
} | |
Buffer(Buffer&& other) | |
: m_raw(other.m_raw) | |
{ | |
other.m_raw = nullptr; | |
} | |
private: | |
// Raw resources that is wrapped by the RAII class | |
// (Remember that `wgpu::Buffer` is actually just a pointer) | |
wgpu::Buffer m_raw; | |
}; | |
} // namespace raii |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment