From 66eb789b41232ecedcca61b987d0860f990938b1 Mon Sep 17 00:00:00 2001 From: Jonas Oreland Date: Fri, 18 Mar 2022 15:04:36 +0100 Subject: [PATCH] Add class for pointer or owned object. To be used as part of field trial conversion effort. Bug: webrtc:10335 Change-Id: Iaeff520d5a83331926ead945c9e414716e61cac8 Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/256013 Reviewed-by: Niels Moller Reviewed-by: Tomas Gunnarsson Reviewed-by: Harald Alvestrand Commit-Queue: Jonas Oreland Cr-Commit-Position: refs/heads/main@{#36259} --- rtc_base/memory/BUILD.gn | 4 +++ rtc_base/memory/always_valid_pointer.h | 40 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 rtc_base/memory/always_valid_pointer.h diff --git a/rtc_base/memory/BUILD.gn b/rtc_base/memory/BUILD.gn index ee66ac0df8..583278ee6e 100644 --- a/rtc_base/memory/BUILD.gn +++ b/rtc_base/memory/BUILD.gn @@ -53,3 +53,7 @@ rtc_library("unittests") { "../../test:test_support", ] } + +rtc_source_set("always_valid_pointer") { + sources = [ "always_valid_pointer.h" ] +} diff --git a/rtc_base/memory/always_valid_pointer.h b/rtc_base/memory/always_valid_pointer.h new file mode 100644 index 0000000000..c73512d3c5 --- /dev/null +++ b/rtc_base/memory/always_valid_pointer.h @@ -0,0 +1,40 @@ +/* + * Copyright 2022 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ +#ifndef RTC_BASE_MEMORY_ALWAYS_VALID_POINTER_H_ +#define RTC_BASE_MEMORY_ALWAYS_VALID_POINTER_H_ + +#include + +namespace webrtc { + +// This template allows the instantiation of a pointer to Interface in such a +// way that if it is passed a null pointer, an object of class Default will be +// created, which will be deallocated when the pointer is deleted. +template +class AlwaysValidPointer { + public: + explicit AlwaysValidPointer(Interface* pointer) + : owned_instance_(pointer ? nullptr : std::make_unique()), + pointer_(pointer ? pointer : owned_instance_.get()) { + RTC_DCHECK(pointer_); + } + + Interface* get() { return pointer_; } + Interface* operator->() { return pointer_; } + Interface& operator*() { return *pointer_; } + + private: + const std::unique_ptr owned_instance_; + Interface* const pointer_; +}; + +} // namespace webrtc + +#endif // RTC_BASE_MEMORY_ALWAYS_VALID_POINTER_H_