Skip to content

Commit

Permalink
Better CesiumImpl implementation.
Browse files Browse the repository at this point in the history
The previous one wouldn't have called derived-class destructors
properly.
  • Loading branch information
kring committed Jan 23, 2025
1 parent 3936614 commit 917f468
Showing 1 changed file with 41 additions and 5 deletions.
46 changes: 41 additions & 5 deletions native~/Shared/src/CesiumImpl.h
Original file line number Diff line number Diff line change
@@ -1,20 +1,56 @@
#pragma once

#include <CesiumUtility/ReferenceCounted.h>
#include <CesiumUtility/Assert.h>

#include <atomic>
#include <cstdint>
#include <type_traits>

namespace CesiumForUnityNative {

template <typename TDerived>
class CesiumImpl
: public CesiumUtility::ReferenceCountedThreadSafe<CesiumImpl<TDerived>> {
template <typename TDerived> class CesiumImpl {
public:
CesiumImpl() = default;
/**
* @brief Adds a counted reference to this object. Use
* {@link CesiumUtility::IntrusivePointer} instead of calling this method
* directly.
*/
void addReference() const /*noexcept*/ { ++this->_referenceCount; }

/**
* @brief Removes a counted reference from this object. When the last
* reference is removed, this method will delete this instance. Use
* {@link CesiumUtility::IntrusivePointer} instead of calling this method
* directly.
*/
void releaseReference() const /*noexcept*/ {
CESIUM_ASSERT(this->_referenceCount > 0);
const int32_t references = --this->_referenceCount;
if (references == 0) {
delete static_cast<const TDerived*>(this);
}
}

/**
* @brief Returns the current reference count of this instance.
*/
std::int32_t getReferenceCount() const noexcept {
return this->_referenceCount;
}

// Prevent copying of impl classes
CesiumImpl(CesiumImpl&&) = delete;
CesiumImpl(const CesiumImpl&) = delete;
CesiumImpl& operator=(CesiumImpl&&) = delete;
CesiumImpl& operator=(const CesiumImpl&) = delete;

private:
CesiumImpl() noexcept = default;
~CesiumImpl() noexcept { CESIUM_ASSERT(this->_referenceCount == 0); }

friend TDerived;

mutable std::atomic<std::int32_t> _referenceCount{0};
};

} // namespace CesiumForUnityNative

0 comments on commit 917f468

Please sign in to comment.