Skip to content

Commit 4caaa47

Browse files
authored
fix optional (assign not working) (#246)
Signed-off-by: turuslan <[email protected]>
1 parent 9f61563 commit 4caaa47

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

include/libp2p/common/final_action.hpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
#include <optional>
1111
#include <utility>
1212

13+
#include <libp2p/common/option_take.hpp>
14+
1315
namespace libp2p::common {
1416

1517
template <typename F>
@@ -44,7 +46,7 @@ namespace libp2p::common {
4446
struct MovableFinalAction {
4547
MovableFinalAction() = delete;
4648
MovableFinalAction(MovableFinalAction &&func)
47-
: func{std::exchange(func.func, {})} {}
49+
: func{qtils::optionTake(func.func)} {}
4850
MovableFinalAction(const MovableFinalAction &func) = delete;
4951
MovableFinalAction &operator=(MovableFinalAction &&func) = delete;
5052
MovableFinalAction &operator=(const MovableFinalAction &func) = delete;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Copyright Quadrivium LLC
3+
* All Rights Reserved
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
7+
#pragma once
8+
9+
#include <optional>
10+
11+
// TODO(turuslan): qtils, https://github.com/qdrvm/kagome/issues/1813
12+
namespace qtils {
13+
/**
14+
* `std::move` doesn't reset `std::optional`.
15+
* Typical bug:
16+
* std::optional<Fn> fn_once;
17+
* if (fn_once) {
18+
* // expected optional to be reset, but it wasn't
19+
* auto fn = std::move(fn_once);
20+
* fn();
21+
* }
22+
*
23+
* `std::exchange` or `std::swap` don't compile because `std::optional` can't
24+
* be assigned.
25+
*
26+
* https://doc.rust-lang.org/std/option/enum.Option.html#method.take
27+
*/
28+
template <typename T>
29+
auto optionTake(std::optional<T> &optional) {
30+
auto result = std::move(optional);
31+
optional.reset();
32+
return result;
33+
}
34+
} // namespace qtils

0 commit comments

Comments
 (0)