mirror of
https://github.com/RGBCube/serenity
synced 2025-05-31 13:38:11 +00:00
LibCore: Introduce ObjectPtr, a step towards reference-counted CObject
Long-term we should use reference counting for the CObject hierarchy. Since we've already accumulated a fair amount of code, this is quite a large task, so I'm breaking it into some steps. So, ObjectPtr is a "smart" pointer for CObject-derived types. It becomes null when moved from, and will destroy unparented CObjects in its destructor. The idea here is to convert the codebase over to ObjectPtr piece by piece, and then when everything is moved and CObject itself refactored for ref-counting, we can just replace ObjectPtr with RefPtr everywhere.
This commit is contained in:
parent
8cfb859368
commit
c34fd10b5b
1 changed files with 53 additions and 0 deletions
53
Libraries/LibCore/ObjectPtr.h
Normal file
53
Libraries/LibCore/ObjectPtr.h
Normal file
|
@ -0,0 +1,53 @@
|
|||
#pragma once
|
||||
|
||||
#include <AK/StdLibExtras.h>
|
||||
|
||||
// This is a stopgap pointer. It's not meant to stick around forever.
|
||||
|
||||
template<typename T>
|
||||
class ObjectPtr {
|
||||
public:
|
||||
ObjectPtr() {}
|
||||
ObjectPtr(T* ptr) : m_ptr(ptr) {}
|
||||
~ObjectPtr()
|
||||
{
|
||||
if (m_ptr && !m_ptr->parent())
|
||||
delete m_ptr;
|
||||
}
|
||||
|
||||
ObjectPtr(const ObjectPtr& other)
|
||||
: m_ptr(other.m_ptr)
|
||||
{
|
||||
}
|
||||
|
||||
ObjectPtr(ObjectPtr&& other)
|
||||
{
|
||||
m_ptr = exchange(other.m_ptr, nullptr);
|
||||
}
|
||||
|
||||
ObjectPtr& operator=(const ObjectPtr& other)
|
||||
{
|
||||
m_ptr = other.m_ptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
ObjectPtr& operator=(ObjectPtr&& other)
|
||||
{
|
||||
if (this != &other) {
|
||||
m_ptr = exchange(other.m_ptr, nullptr);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
T* operator->() { return m_ptr; }
|
||||
const T* operator->() const { return m_ptr; }
|
||||
|
||||
operator T*() { return m_ptr; }
|
||||
operator const T*() const { return m_ptr; }
|
||||
|
||||
T& operator*() { return *m_ptr; }
|
||||
const T& operator*() const { return *m_ptr; }
|
||||
|
||||
private:
|
||||
T* m_ptr { nullptr };
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue