Skip to content

Commit 6b0154b

Browse files
authoredMar 4, 2025··
memory: Add shared pointer reinterpretPointerCast function (#47)
* memory: Add force reinterpret constructor to shared pointer * memory: Change constructor to reinterpretPointerCast function * memory: Add reinterpretPointerCast test
1 parent 61a5382 commit 6b0154b

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed
 

‎include/hyprutils/memory/SharedPtr.hpp

+7-2
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ namespace Hyprutils {
144144
Impl_::impl_base* impl_ = nullptr;
145145

146146
private:
147-
/*
147+
/*
148148
no-op if there is no impl_
149149
may delete the stored object if ref == 0
150150
may delete and reset impl_ if ref == 0 and weak == 0
@@ -167,7 +167,7 @@ namespace Hyprutils {
167167
impl_->inc();
168168
}
169169

170-
/* destroy the pointed-to object
170+
/* destroy the pointed-to object
171171
if able, will also destroy impl */
172172
void destroyImpl() {
173173
// destroy the impl contents
@@ -185,6 +185,11 @@ namespace Hyprutils {
185185
static CSharedPointer<U> makeShared(Args&&... args) {
186186
return CSharedPointer<U>(new U(std::forward<Args>(args)...));
187187
}
188+
189+
template <typename T, typename U>
190+
CSharedPointer<T> reinterpretPointerCast(const CSharedPointer<U>& ref) {
191+
return CSharedPointer<T>(ref.impl_);
192+
}
188193
}
189194
}
190195

‎tests/memory.cpp

+11-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ using namespace Hyprutils::Memory;
1111

1212
int main(int argc, char** argv, char** envp) {
1313
SP<int> intPtr = makeShared<int>(10);
14-
SP<int> intPtr2 = makeShared<int>(1337);
14+
SP<int> intPtr2 = makeShared<int>(-1337);
1515
UP<int> intUnique = makeUnique<int>(420);
1616

1717
int ret = 0;
@@ -52,5 +52,15 @@ int main(int argc, char** argv, char** envp) {
5252
EXPECT(weak.expired(), true);
5353
EXPECT(weakUnique.expired(), true);
5454

55+
auto intPtr2AsUint = reinterpretPointerCast<unsigned int>(intPtr2);
56+
EXPECT(intPtr2.strongRef(), 4);
57+
EXPECT(intPtr2AsUint.strongRef(), 4);
58+
59+
EXPECT(*intPtr2AsUint > 0, true);
60+
EXPECT(*intPtr2AsUint, (unsigned int)(int)-1337);
61+
*intPtr2AsUint = 10;
62+
EXPECT(*intPtr2AsUint, 10);
63+
EXPECT(*intPtr2, 10);
64+
5565
return ret;
5666
}

0 commit comments

Comments
 (0)
Please sign in to comment.