Android本机强指针vs std :: shared

编程入门 行业动态 更新时间:2024-10-24 14:23:41
本文介绍了Android本机强指针vs std :: shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我指的是 Refbase.h , Refbase.cpp 和 StrongPointer.h

在Android强指针实现中,任何基于强指针的对象都必须继承refbase即

In the Android implementation of strong pointer, any strong-pointer based object must inherit refbase i.e.

sp<TheClass> theObj // TheClass must inherit from class RefBase

此要求可以在sp方法之一的代码中看到:

This requirement can be seen in the code for one of sp's methods:

template<typename T> sp<T>& sp<T>::operator =(T* other) { if (other != NULL) { other->incStrong(this); } if (mPtr != NULL) { mPtr->decStrong(this); } mPtr = other; return *this; }

为了使对incStrong或decStrong的调用不会失败. . . other和mPtr必须继承了RefBase

In order for call to incStrong or decStrong to not fail . . . other and mPtr must have inherited RefBase

问题

为什么要实现sp,使得要求管理的obj是RefBase的子代?甚至没有办法在编译时甚至运行时强制执行此要求. (也许if(type()...)

Why is sp implemented such that the obj that it's managing is required to be a child of RefBase? There's not even a way to enforce this requirement at compile-time or even runtime. (Well maybe if(type()...)

标准库没有这样的要求

... 经过进一步思考,是否可以提供灵活性的答案? 如果是,那么如何提供灵活性?

... Upon further thought, is the answer that this provides flexibility? If yes, how does this provide flexibility?

推荐答案

它自动允许您从任何实现RefBase的对象中创建sp,而对于共享指针,您可以在尝试将原始指针包装到共享对象中时大开眼界.

It automatically allows you to create sp from any object implementing RefBase, while for shared pointer you can shoot yourself in the foot while trying to wrap raw pointer into shared one.

因此,对于shared_ptr来说,您可能需要这样做: en.cppreference/w/cpp/memory/enable_shared_from_this

So while for shared_ptr you might need this: en.cppreference/w/cpp/memory/enable_shared_from_this

对于sp,您几乎可以安全地将原始指针传递给sp构造器.

for sp you can almost safely pass raw pointer to sp contructor.

更多推荐

Android本机强指针vs std :: shared

本文发布于:2023-07-30 00:26:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1244953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:本机   指针   Android   std   shared

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!