Skip to content

Commit 42e2946

Browse files
[libc][NFC] add arrow operator to optional
Reviewed By: sivachandra Differential Revision: https://reviews.llvm.org/D131610
1 parent 497705f commit 42e2946

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

libc/src/__support/CPP/optional.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ template <class T> class optional {
7474
constexpr T &operator*() & { return Storage.StoredValue; }
7575

7676
constexpr const T &operator*() const & { return Storage.StoredValue; }
77+
78+
constexpr T *operator->() { return &Storage.StoredValue; }
79+
80+
constexpr const T *operator->() const { return &Storage.StoredValue; }
7781
};
7882
} // namespace cpp
7983
} // namespace __llvm_libc

libc/test/src/__support/CPP/optional_test.cpp

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,19 @@
1212
using __llvm_libc::cpp::nullopt;
1313
using __llvm_libc::cpp::optional;
1414

15-
// This has clase has two properties for testing:
16-
// 1) No default constructor
17-
// 2) A non-trivial destructor with an observable side-effect
15+
// This class has three properties for testing:
16+
// 1) No default constructor.
17+
// 2) A non-trivial destructor with an observable side-effect.
18+
// 3) Functions that can be called explicitly.
1819
class Contrived {
1920
int *_a;
2021

2122
public:
2223
Contrived(int *a) : _a(a) {}
2324
~Contrived() { (*_a)++; }
25+
26+
int get_a() { return *_a; }
27+
void inc_a() { (*_a)++; }
2428
};
2529

2630
TEST(LlvmLibcOptionalTest, Tests) {
@@ -59,4 +63,16 @@ TEST(LlvmLibcOptionalTest, Tests) {
5963
ASSERT_FALSE(Trivial5.has_value());
6064
optional<int> Trivial6 = Trivial5;
6165
ASSERT_FALSE(Trivial6.has_value());
66+
67+
// Test operator->
68+
int arrow_num = 5;
69+
optional<Contrived> arrow_test(&arrow_num);
70+
ASSERT_TRUE(arrow_test.has_value());
71+
ASSERT_EQ(arrow_test->get_a(), arrow_num);
72+
arrow_num = 10;
73+
ASSERT_EQ(arrow_test->get_a(), arrow_num);
74+
arrow_test->inc_a();
75+
ASSERT_EQ(arrow_test->get_a(), arrow_num);
76+
ASSERT_EQ(arrow_num, 11);
77+
arrow_test.reset();
6278
}

0 commit comments

Comments
 (0)