Skip to content

Commit 3b6b9eb

Browse files
author
Gabriel Schulhof
committed
AsyncWorker: introduce Destroy() method
`AsyncWorker` contained the assumption that instances of its subclasses were allocated using `new`, because it unconditionally destroyed instances using `delete`. This change replaces the call to `delete` with a call to a protected instance method `Destroy()`, which can be overridden by subclasses. This ensures that users can employ their own allocators when creating `AsyncWorker` subclass instances because they can override the `Destroy()` method to use their deallocator of choice. Re: #231 (comment) PR-URL: #488 Reviewed-By: Michael Dawson <[email protected]>
1 parent f633fbd commit 3b6b9eb

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

doc/async_worker.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,19 @@ class was created, passing in the error as the first parameter.
125125
virtual void Napi::AsyncWorker::OnError(const Napi::Error& e);
126126
```
127127
128+
### Destroy
129+
130+
This method is invoked when the instance must be deallocated. If
131+
`SuppressDestruct()` was not called then this method will be called after either
132+
`OnError()` or `OnOK()` complete. The default implementation of this method
133+
causes the instance to delete itself using the `delete` operator. The method is
134+
provided so as to ensure that instances allocated by means other than the `new`
135+
operator can be deallocated upon work completion.
136+
137+
```cpp
138+
virtual void Napi::AsyncWorker::Destroy();
139+
```
140+
128141
### Constructor
129142

130143
Creates a new `Napi::AsyncWorker`.

napi-inl.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3529,6 +3529,10 @@ inline AsyncWorker::~AsyncWorker() {
35293529
}
35303530
}
35313531

3532+
inline void AsyncWorker::Destroy() {
3533+
delete this;
3534+
}
3535+
35323536
inline AsyncWorker::AsyncWorker(AsyncWorker&& other) {
35333537
_env = other._env;
35343538
other._env = nullptr;
@@ -3623,7 +3627,7 @@ inline void AsyncWorker::OnWorkComplete(
36233627
});
36243628
}
36253629
if (!self->_suppress_destruct) {
3626-
delete self;
3630+
self->Destroy();
36273631
}
36283632
}
36293633

napi.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1803,6 +1803,7 @@ namespace Napi {
18031803
virtual void Execute() = 0;
18041804
virtual void OnOK();
18051805
virtual void OnError(const Error& e);
1806+
virtual void Destroy();
18061807

18071808
void SetError(const std::string& error);
18081809

0 commit comments

Comments
 (0)