Skip to content

Merge ref_info free functions into ref_info #5

@kammce

Description

@kammce

All of these can just be member functions of ref_info so we might as well do so.

/**
 * @brief Add strong reference to control block
 *
 * @param p_info Pointer to the control block
 */
inline void ptr_add_ref(ref_info* p_info)
{
  p_info->strong_count.fetch_add(1, std::memory_order_relaxed);
}

/**
 * @brief Release strong reference from control block
 *
 * If this was the last strong reference, the pointed-to object will be
 * destroyed. If there are no remaining weak references, the memory
 * will also be deallocated.
 *
 * @param p_info Pointer to the control block
 */
inline void ptr_release(ref_info* p_info)
{
  if (p_info->strong_count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
    // No more strong references, destroy the object but keep control block
    // if there are weak references

    // Call the destroy function which will:
    // 1. Call the destructor of the object
    // 2. Return the size of the rc for deallocation when needed
    usize const object_size = p_info->destroy(p_info);

    // If there are no weak references, deallocate memory
    if (p_info->weak_count.load(std::memory_order_acquire) == 0) {
      // Save allocator for deallocating
      auto alloc = p_info->allocator;

      // Deallocate memory
      alloc.deallocate_bytes(p_info, object_size);
    }
  }
}

/**
 * @brief Add weak reference to control block
 *
 * @param p_info Pointer to the control block
 */
inline void ptr_add_weak(ref_info* p_info)
{
  p_info->weak_count.fetch_add(1, std::memory_order_relaxed);
}

/**
 * @brief Release weak reference from control block
 *
 * If this was the last weak reference and there are no remaining
 * strong references, the memory will be deallocated.
 *
 * @param p_info Pointer to the control block
 */
inline void ptr_release_weak(ref_info* p_info)
{
  if (p_info->weak_count.fetch_sub(1, std::memory_order_acq_rel) == 0) {
    // No more weak references, check if we can deallocate
    if (p_info->strong_count.load(std::memory_order_acquire) == 0) {
      // No strong references either, get the size from the destroy function
      auto const object_size = p_info->destroy(nullptr);

      // Save allocator for deallocating
      auto alloc = p_info->allocator;

      // Deallocate memory
      alloc.deallocate_bytes(p_info, object_size);
    }
  }
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions