shared_ptr 是 C++11 中引入的一种智能指针,它可以在多个指针之间共享同一个对象,从而避免了内存泄漏和野指针的问题。shared_ptr 的实现方式通常是基于引用计数的技术,具体来说,每个 shared_ptr 对象都会维护一个引用计数器,用于记录有多少个指针指向同一个对象。当引用计数器为 0 时,表示没有任何指针指向该对象,此时会自动释放该对象的内存空间。
#include <iostream>
#include <vector>
#include <unordered_set>
template <typename T>
class shared_ptr {
private:
T* ptr;
int* ref_count;
void release() {
if (ref_count) {
--(*ref_count);
if (*ref_count == 0) {
delete ptr;
delete ref_count;
}
ptr = nullptr;
ref_count = nullptr;
}
}
public:
shared_ptr() : ptr(nullptr), ref_count(nullptr) {}
shared_ptr(T* p) : ptr(p), ref_count(new int(1)) {}
shared_ptr(const shared_ptr& other) : ptr(other.ptr), ref_count(other.ref_count) {
if (ref_count) {
++(*ref_count);
}
}
~shared_ptr() {
release();
}
shared_ptr& operator=(const shared_ptr& other) {
if (this != &other) {
release();
ptr = other.ptr;
ref_count = other.ref_count;
if (ref_count) {
++(*ref_count);
}
}
return *this;
}
T* get() const {
return ptr;
}
int use_count() const {
return ref_count ? *ref_count : 0;
}
void reset() {
release();
}
void reset(T* p) {
release();
ptr = p;
ref_count = new int(1);
}
T& operator*() const {
return *ptr;
}
T* operator->() const {
return ptr;
}
};
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor" << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor" << std::endl;
}
void hello() {
std::cout << "Hello, world!" << std::endl;
}
};
int main() {
shared_ptr<MyClass> ptr1(new MyClass());
shared_ptr<MyClass> ptr2 = ptr1;
std::cout << "ptr1 use count: " << ptr1.use_count() << std::endl;
std::cout << "ptr2 use count: " << ptr2.use_count() << std::endl;
ptr1->hello();
ptr2.reset();
std::cout << "ptr1 use count: " << ptr1.use_count() << std::endl;
std::cout << "ptr2 use count: " << ptr2.use_count() << std::endl;
return 0;
}
在这个实现方式中,我们定义了一个名为 shared_ptr 的类模板,它包含了指向对象的指针 ptr 和引用计数器 ref_count。在构造函数中,我们将 ref_count 初始化为 1,表示有一个指针指向该对象。在拷贝构造函数和赋值运算符中,我们将 ref_count 的值加 1,表示有一个新的指针指向该对象。在析构函数中,我们将 ref_count 的值减 1,如果 ref_count 的值为 0,则表示没有任何指针指向该对象,此时会自动释放该对象的内存空间。
在使用 shared_ptr 时,我们可以通过 get 函数获取指向对象的指针,通过 use_count 函数获取当前有多少个指针指向该对象。同时,我们还可以通过 reset 函数释放当前指针,并重新指向一个新的对象。此外,我们还可以通过 operator* 和 operator-> 运算符重载,使得 shared_ptr 对象可以像普通指针一样使用。
总之,shared_ptr 是一种非常实用的智能指针,它可以在多个指针之间共享同一个对象,从而避免了内存泄漏和野指针的问题。在实际开发中,我们可以根据需要灵活地使用 shared_ptr,提高代码的可读性和可维护性。
打印:
static变量可以被多个变量共享,但是这种共享方式是基于静态存储期的,而不是基于动态存储期的。具体来说,当我们定义一个static变量时,它会在程序运行期间一直存在,直到程序结束才会被销毁。在这个过程中,所有使用该static变量的变量都会共享同一个内存空间,从而实现了多变量共享的功能。综上所述,虽然
static变量可以实现多变量共享的功能,但是在实现shared_ptr这样需要动态存储期共享的功能时,使用引用计数是更为合适的选择。
No comments yet.