Skip to content

Commit 2dc1f5b

Browse files
authored
Merge pull request #1065 from strager/move-only-functor
src,test: allow creating Function with move-only functor
2 parents 2b57a4a + 3e5897a commit 2dc1f5b

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

napi-inl.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <cstring>
1515
#include <mutex>
1616
#include <type_traits>
17+
#include <utility>
1718

1819
namespace Napi {
1920

@@ -2156,7 +2157,7 @@ inline Function Function::New(napi_env env,
21562157
void* data) {
21572158
using ReturnType = decltype(cb(CallbackInfo(nullptr, nullptr)));
21582159
using CbData = details::CallbackData<Callable, ReturnType>;
2159-
auto callbackData = new CbData({ cb, data });
2160+
auto callbackData = new CbData{std::move(cb), data};
21602161

21612162
napi_value value;
21622163
napi_status status = CreateFunction(env,

test/function.cc

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#include <memory>
12
#include "napi.h"
23
#include "test_helper.h"
34

@@ -271,5 +272,24 @@ Object InitFunction(Env env) {
271272
exports["callWithFunctionOperator"] =
272273
Function::New<CallWithFunctionOperator>(env);
273274
result["templated"] = exports;
275+
276+
exports = Object::New(env);
277+
exports["lambdaWithNoCapture"] =
278+
Function::New(env, [](const CallbackInfo& info) {
279+
auto env = info.Env();
280+
return Boolean::New(env, true);
281+
});
282+
exports["lambdaWithCapture"] =
283+
Function::New(env, [data = 42](const CallbackInfo& info) {
284+
auto env = info.Env();
285+
return Boolean::New(env, data == 42);
286+
});
287+
exports["lambdaWithMoveOnlyCapture"] = Function::New(
288+
env, [data = std::make_unique<int>(42)](const CallbackInfo& info) {
289+
auto env = info.Env();
290+
return Boolean::New(env, *data == 42);
291+
});
292+
result["lambda"] = exports;
293+
274294
return result;
275295
}

test/function.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const assert = require('assert');
55
module.exports = require('./common').runTest(binding => {
66
test(binding.function.plain);
77
test(binding.function.templated);
8+
testLambda(binding.function.lambda);
89
});
910

1011
function test(binding) {
@@ -112,3 +113,9 @@ function test(binding) {
112113
binding.makeCallbackWithInvalidReceiver(() => {});
113114
});
114115
}
116+
117+
function testLambda(binding) {
118+
assert.ok(binding.lambdaWithNoCapture());
119+
assert.ok(binding.lambdaWithCapture());
120+
assert.ok(binding.lambdaWithMoveOnlyCapture());
121+
}

0 commit comments

Comments
 (0)