eliemichel/WebGPU-Cpp

Default constructor for types

qhdwight opened this issue ยท 5 comments

What do we think about default constructors for every type?

A common idiom for RAII is for objects to have an "empty" state. Consider std::unique_ptr (null), std::vector (empty), etc. This is also the state assumed when you move the resources away from an object.

Currently I need to wrap all my types in a std::optional and it is a little tedious.

Actually found a temporary solution.

The problem was I had a struct which embedded wgpu variables. For example a wgpu::Instance. I can just change the definition to:

struct MyStruct {
    ...
    wgpu::Instance mInstance = nullptr;
    ...
}

I think default ctors should be added to mimic the above behavior.

Yep I should add a default constructor that initializes to nullptr indeed I noted this already and forgot!

Note however that this is not a RAII wrapper, rather a 0-overhead wrapper: it is only about syntactic sugar, and has no hidden behavior (well actually it initializes nextInChain to nullptr, but it's the only extra behavior compared to the C API). I have a RAII wrapper as well that I plan on adding as an option here (in something like webgpu-raii.hpp) but didn't find the time to clean it up yet!

Uh oh... that means I am not freeing a LOT of resources. Thank you for the heads up.

Love the tutorials by the way. Super helpful.

It may also be nice to add support for designed initializers added in C++20: https://en.cppreference.com/w/cpp/language/aggregate_initialization

Handles are now initialized to nullptr by default!