diff options
author | Steven Moreland <smoreland@google.com> | 2021-04-05 20:36:34 +0000 |
---|---|---|
committer | Steven Moreland <smoreland@google.com> | 2021-04-07 20:30:21 +0000 |
commit | 1d68548823d7b1e0bd186b924821cdbd80767be1 (patch) | |
tree | 5376fc2abbd1387f30437bc23bbd88358fb5bc96 | |
parent | b20e9a36061f324f1775d100663779a962b033eb (diff) | |
download | core-1d68548823d7b1e0bd186b924821cdbd80767be1.tar.gz |
libutils: add sp::cast method
Previously, sp::sp(T*) internally had a static cast, and people
frequently wrote code like this:
sp<A> a = ...;
sp<B> b(a.get()); // implicit static cast
Luckily, none of the other sp constructors have this implicit cast. So,
for explicit code, rather than making those use static_cast internally,
adding an sp::cast function.
Bug: 184190315
Test: use in libbinder
Change-Id: Id205c88d03e16cf85ccb8f493ce88b4bbc65a688
-rw-r--r-- | libutils/include/utils/StrongPointer.h | 12 |
1 files changed, 12 insertions, 0 deletions
diff --git a/libutils/include/utils/StrongPointer.h b/libutils/include/utils/StrongPointer.h index 1f070524a..dd53b9ec0 100644 --- a/libutils/include/utils/StrongPointer.h +++ b/libutils/include/utils/StrongPointer.h @@ -72,6 +72,12 @@ public: template<typename U> sp(const sp<U>& other); // NOLINT(implicit) template<typename U> sp(sp<U>&& other); // NOLINT(implicit) + // Cast a strong pointer directly from one type to another. Constructors + // allow changing types, but only if they are pointer-compatible. This does + // a static_cast internally. + template <typename U> + static inline sp<T> cast(const sp<U>& other); + ~sp(); // Assignment @@ -279,6 +285,12 @@ sp<T>::sp(sp<U>&& other) other.m_ptr = nullptr; } +template <typename T> +template <typename U> +sp<T> sp<T>::cast(const sp<U>& other) { + return sp<T>::fromExisting(static_cast<T*>(other.get())); +} + template<typename T> sp<T>::~sp() { if (m_ptr) |