1
0
Fork 0
mirror of https://github.com/ossrs/srs.git synced 2025-03-09 15:49:59 +00:00

SmartPtr: Use shared ptr to manage GB objects. v6.0.126 (#4080)

The object relations: 

![gb](266e8a4e-3f1e-4805-8406-9008d6a63aa0)

Session manages SIP and Media object using shared resource or shared
ptr. Note that I actually use SrsExecutorCoroutine to delete the object
when each coroutine is done, because there is always a dedicate
coroutine for each object.

For SIP and Media object, they directly use the session by raw pointer,
it's safe because session always live longer than session and media
object.

---

Co-authored-by: Jacob Su <suzp1984@gmail.com>
This commit is contained in:
Winlin 2024-06-12 22:40:20 +08:00 committed by GitHub
parent 1656391c67
commit 6834ec208d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 989 additions and 464 deletions

View file

@ -81,4 +81,103 @@ public:
}
};
// Shared ptr smart pointer, see https://github.com/ossrs/srs/discussions/3667#discussioncomment-8969107
// Usage:
// SrsSharedPtr<MyClass> ptr(new MyClass());
// ptr->do_something();
//
// SrsSharedPtr<MyClass> cp = ptr;
// cp->do_something();
template<class T>
class SrsSharedPtr
{
private:
// The pointer to the object.
T* ptr_;
// The reference count of the object.
uint32_t* ref_count_;
public:
// Create a shared ptr with the object.
SrsSharedPtr(T* ptr) {
ptr_ = ptr;
ref_count_ = new uint32_t(1);
}
// Copy the shared ptr.
SrsSharedPtr(const SrsSharedPtr<T>& cp) {
copy(cp);
}
// Dispose and delete the shared ptr.
virtual ~SrsSharedPtr() {
reset();
}
private:
// Reset the shared ptr.
void reset() {
if (!ref_count_) return;
(*ref_count_)--;
if (*ref_count_ == 0) {
delete ptr_;
delete ref_count_;
}
ptr_ = NULL;
ref_count_ = NULL;
}
// Copy from other shared ptr.
void copy(const SrsSharedPtr<T>& cp) {
ptr_ = cp.ptr_;
ref_count_ = cp.ref_count_;
if (ref_count_) (*ref_count_)++;
}
// Move from other shared ptr.
void move(SrsSharedPtr<T>& cp) {
ptr_ = cp.ptr_;
ref_count_ = cp.ref_count_;
cp.ptr_ = NULL;
cp.ref_count_ = NULL;
}
public:
// Get the object.
T* get() {
return ptr_;
}
// Overload the -> operator.
T* operator->() {
return ptr_;
}
// The assign operator.
SrsSharedPtr<T>& operator=(const SrsSharedPtr<T>& cp) {
if (this != &cp) {
reset();
copy(cp);
}
return *this;
}
private:
// Overload the * operator.
T& operator*() {
return *ptr_;
}
// Overload the bool operator.
operator bool() const {
return ptr_ != NULL;
}
#if __cplusplus >= 201103L // C++11
public:
// The move constructor.
SrsSharedPtr(SrsSharedPtr<T>&& cp) {
move(cp);
};
// The move assign operator.
SrsSharedPtr<T>& operator=(SrsSharedPtr<T>&& cp) {
if (this != &cp) {
reset();
move(cp);
}
return *this;
};
#endif
};
#endif

View file

@ -9,6 +9,6 @@
#define VERSION_MAJOR 6
#define VERSION_MINOR 0
#define VERSION_REVISION 125
#define VERSION_REVISION 126
#endif