Skip to content

Commit 93d0f63

Browse files
Hao Lufacebook-github-bot
Hao Lu
authored andcommitted
[c10] Add default constructor to Maybeowned (pytorch#55128)
Summary: Pull Request resolved: pytorch#55128 Test Plan: CI Reviewed By: swolchok Differential Revision: D27495079 fbshipit-source-id: 3bd01956a8b65170d6b38096dbd15c4809904f88
1 parent ec609e7 commit 93d0f63

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

Diff for: c10/test/util/MaybeOwned_test.cpp

+11
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ TEST(MaybeOwnedTest, SimpleDereferencingString) {
3535
EXPECT_EQ(owned2->size(), x.size());
3636
}
3737

38+
TEST(MaybeOwnedTest, DefaultCtorInt) {
39+
int x = 123;
40+
MaybeOwned<int> borrowed, owned;
41+
borrowed = MaybeOwned<int>::borrowed(x);
42+
owned = MaybeOwned<int>::owned(c10::in_place, x);
43+
EXPECT_EQ(*borrowed, x);
44+
EXPECT_EQ(*owned, x);
45+
EXPECT_EQ(&*borrowed, &x);
46+
EXPECT_NE(&*owned, &x);
47+
}
48+
3849
TEST(MaybeOwnedTest, MoveConstructor) {
3950
std::string x = "hello";
4051
auto borrowed = MaybeOwned<std::string>::borrowed(x);

Diff for: c10/util/MaybeOwned.h

+7-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ class MaybeOwned final {
3737
, own_(std::forward<Args>(args)...) {}
3838

3939
public:
40-
40+
explicit MaybeOwned(): isBorrowed_(true), borrow_(nullptr) {}
4141
MaybeOwned(const MaybeOwned&) = delete;
4242
MaybeOwned& operator=(const MaybeOwned&) = delete;
4343

@@ -91,10 +91,16 @@ class MaybeOwned final {
9191
}
9292

9393
const T& operator*() const {
94+
if (isBorrowed_) {
95+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(borrow_ != nullptr);
96+
}
9497
return isBorrowed_ ? *borrow_ : own_;
9598
}
9699

97100
const T* operator->() const {
101+
if (isBorrowed_) {
102+
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(borrow_ != nullptr);
103+
}
98104
return isBorrowed_ ? borrow_ : &own_;
99105
}
100106
};

0 commit comments

Comments
 (0)