AlexvZyl / NativeFramework

💡 A GPU-accelerated native application framework, with performance and scalability at its core. Written in C++ using GLFW, OpenGL and dear imgui.
4 stars 1 forks source link

Wrapping smart pointers #279

Open AlexvZyl opened 2 years ago

AlexvZyl commented 2 years ago

@Cullen-Enerdyne What do you think about doing something like this:

Create a new type UPtr that is just std::unique_ptr().

template <typename T>
using UPtr = std::unique_ptr<T>;

We can if we want to expand it to be a class at a later stage for resource management.

The Cherno does something similar for his engine.

Cullen-Enerdyne commented 2 years ago

Why would we want a wrapper?

AlexvZyl commented 2 years ago

I have been thinking about this.

One reason people wrap smart pointers is for resource counting. We can have a static variable, so we can get the current shader count like this:

UPtr<Shader>::count;

Another reason is to make it easier to create pointers. Currently, we have to do this:

std::unique_ptr<GraphicsTrianglesBuffer<VertexDataTextured>> s_unitQuad;
s_unitQuad = std::make_unique<GraphicsTrianglesBuffer<VertexDataTextured>>();

If we wrap the pointers we can do this:

UPtr<GraphicsTrianglesBuffer<VertexDataTextured>> s_unitQuad;
s_unitQuad.make();

We can then overload the arrow operator so that it acts like a normal smart pointer.

The Cherno wraps them (a bit differently) in his engine.

In addition to this, we can overload comparison operators so that this is a valid comparison:

UPtr<MyClass> myPtr1;
myPtr1.make();
MyClass* myPtr2 = myPtr1.get();
// We can also overload the above assignment so that you only have to do this:
// MyClass* myPtr2 = myPtr1; 
if(myPtr1 == myPtr2) // This does not work with normal smart pointers.
{ }

This is useful for when using std algorithms.

AlexvZyl commented 2 years ago

We could also use variadic templates to construct the pointer in place. This:

UPtr<MyClass> myPtr1;
myPtr1.make();

is the same as this:

UPtr<MyClass> myPtr1();