Skip to content

Commit

Permalink
Move result out of Future instead of copying it
Browse files Browse the repository at this point in the history
Example: `auto ptr = djinni::Promise<std::unique_ptr<int>>::resolve(nullptr).get();`
Before this didn't work (called copy constructor of unique_ptr), now it does.
  • Loading branch information
jb-gcx committed Jul 10, 2024
1 parent 9a74ee9 commit f224408
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
6 changes: 3 additions & 3 deletions support-lib/cpp/Future.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ template <typename T>
struct ValueHolder {
using type = T;
std::optional<T> value;
T getValueUnsafe() const {return *value;}
T&& getValueUnsafe() && {return std::move(*value);}
};
template <>
struct ValueHolder<void> {
using type = bool;
std::optional<bool> value;
void getValueUnsafe() const {}
void getValueUnsafe() && {}
};

template<typename T>
Expand Down Expand Up @@ -295,7 +295,7 @@ class Future {
sharedState->cv.wait(lk, [state = sharedState] {return state->isReady();});
#endif
if (!sharedState->exception) {
return sharedState->getValueUnsafe();
return std::move(*sharedState).getValueUnsafe();
} else {
std::rethrow_exception(sharedState->exception);
}
Expand Down
29 changes: 29 additions & 0 deletions test-suite/handwritten-src/objc/tests/DBCppFutureTests.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#import <XCTest/XCTest.h>

#include <Future.hpp>

@interface DBCppFutureTests : XCTestCase

@end

@implementation DBCppFutureTests

- (void)setUp
{
[super setUp];
}

- (void)tearDown
{
[super tearDown];
}

- (void)testCppFutureMovesResult
{
auto future = djinni::Promise<std::unique_ptr<int>>::resolve(std::make_unique<int>(5));
auto ptr = future.get();
XCTAssertTrue(!!ptr);
XCTAssertEqual(*ptr, 5);
}

@end

0 comments on commit f224408

Please sign in to comment.