Skip to content

Commit b7743d8

Browse files
authored
fix: throw error when accessing disposed objects (#3043)
1 parent 74624c0 commit b7743d8

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

packages/skia/cpp/api/JsiSkHostObjects.h

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -54,20 +54,21 @@ template <typename T> class JsiSkWrappingHostObject : public JsiSkHostObject {
5454

5555
/**
5656
* Returns the underlying object exposed by this host object. This object
57-
* should be wrapped in a shared pointer of some kind
57+
* should be wrapped in a shared pointer of some kind.
58+
* Throws if the object has been disposed.
5859
* @return Underlying object
5960
*/
60-
T getObject() { return _object; }
61-
const T getObject() const { return _object; }
61+
T getObject() { return validateObject(); }
62+
const T getObject() const { return validateObject(); }
6263

6364
/**
64-
Updates the inner object with a new version of the object.
65+
* Updates the inner object with a new version of the object.
6566
*/
6667
void setObject(T object) { _object = object; }
6768

6869
/**
69-
Dispose function that can be exposed to JS by using the JSI_API_TYPENAME
70-
macro
70+
* Dispose function that can be exposed to JS by using the JSI_API_TYPENAME
71+
* macro.
7172
*/
7273
JSI_HOST_FUNCTION(dispose) {
7374
safeDispose();
@@ -76,12 +77,22 @@ template <typename T> class JsiSkWrappingHostObject : public JsiSkHostObject {
7677

7778
protected:
7879
/**
79-
Override to implement disposale of allocated resources like smart pointers
80-
etc. This method will only be called once for each instance of this class.
80+
* Override to implement disposal of allocated resources like smart pointers.
81+
* This method will only be called once for each instance of this class.
8182
*/
8283
virtual void releaseResources() = 0;
8384

8485
private:
86+
/**
87+
* Validates that _object was not disposed and returns it.
88+
*/
89+
T validateObject() const {
90+
if (_isDisposed) {
91+
throw std::runtime_error("Attempted to access a disposed object.");
92+
}
93+
return _object;
94+
}
95+
8596
void safeDispose() {
8697
if (!_isDisposed) {
8798
_isDisposed = true;
@@ -90,12 +101,12 @@ template <typename T> class JsiSkWrappingHostObject : public JsiSkHostObject {
90101
}
91102

92103
/**
93-
* Wrapped object
104+
* Wrapped object.
94105
*/
95106
T _object;
96107

97108
/**
98-
Resource disposed flag
109+
* Resource disposed flag.
99110
*/
100111
std::atomic<bool> _isDisposed = {false};
101112
};

0 commit comments

Comments
 (0)