Skip to content

Commit 2179962

Browse files
committed
Don't co-allocate ref count by default
1 parent 061f3c1 commit 2179962

1 file changed

Lines changed: 31 additions & 4 deletions

File tree

include/vsg/core/ref_ptr.h

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,16 @@ namespace vsg
130130
assignTo(*_ptr);
131131
}
132132

133+
template<class... Args>
134+
explicit RefCountPointer(Args&&... args) :
135+
RefCountBase(),
136+
_ptr(new T(this, std::forward<Args>(args)...))
137+
{
138+
assignTo(*_ptr);
139+
}
140+
141+
T* _ptr;
142+
133143
private:
134144
void destroyResource() noexcept override
135145
{
@@ -140,8 +150,6 @@ namespace vsg
140150
{
141151
delete this;
142152
}
143-
144-
T* _ptr;
145153
};
146154

147155
template<class T, class = void>
@@ -435,9 +443,28 @@ namespace vsg
435443
element_type* _ptr = nullptr;
436444
};
437445

438-
// like std::make_shared
446+
// like std::make_shared, but allocates the ref count separately
439447
template<class T, class... Args>
440448
[[nodiscard]] ref_ptr<T> make_referenced(Args&&... args)
449+
{
450+
if constexpr (detail::NeedsRefCountEarly<T>::value)
451+
{
452+
auto* controlBlock = new detail::RefCountPointer<T>(std::forward<Args>(args)...);
453+
detail::TemporaryOwner<T> temp{controlBlock->_ptr};
454+
return ref_ptr<T>(temp);
455+
}
456+
else
457+
{
458+
auto* instance = new T(std::forward<Args>(args)...);
459+
new detail::RefCountPointer<T>(instance);
460+
detail::TemporaryOwner<T> temp{instance};
461+
return ref_ptr<T>(temp);
462+
}
463+
}
464+
465+
// like std::make_shared
466+
template<class T, class... Args>
467+
[[nodiscard]] ref_ptr<T> make_referenced_adjacent_ref_count(Args&&... args)
441468
{
442469
auto* controlBlock = new detail::RefCountWithObject<T>(std::forward<Args>(args)...);
443470
detail::TemporaryOwner<T> temp{std::addressof(controlBlock->storage)};
@@ -446,7 +473,7 @@ namespace vsg
446473

447474
// like std::allocate_shared
448475
template<class T, class Alloc, class... Args>
449-
[[nodiscard]] ref_ptr<T> allocate_referenced(const Alloc& allocator, Args&&... args)
476+
[[nodiscard]] ref_ptr<T> allocate_referenced_adjacent_ref_count(const Alloc& allocator, Args&&... args)
450477
{
451478
using ControlBlock = detail::RefCountWithObjectAndAllocator<std::remove_cv_t<T>, Alloc>;
452479
auto reboundAlloc = typename ControlBlock::Rebound(allocator);

0 commit comments

Comments
 (0)