C++ 智能指针 shared_ptr 使用指南:详解创建、释放和使用示例
智能指针 'shared_ptr' 是 C++11 引入的,用于管理动态分配的内存,它可以自动进行内存的释放,避免了手动释放内存的繁琐和容易出错的问题。
使用 'shared_ptr' 需要包含 '
以下是使用 'shared_ptr' 的示例说明:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << 'MyClass 构造函数被调用' << std::endl;
}
~MyClass() {
std::cout << 'MyClass 析构函数被调用' << std::endl;
}
void doSomething() {
std::cout << 'do something' << std::endl;
}
};
int main() {
std::shared_ptr<MyClass> ptr(new MyClass); // 创建一个 MyClass 类型的 shared_ptr 对象
ptr->doSomething(); // 使用箭头运算符访问成员函数
// 使用智能指针作为函数参数
std::shared_ptr<MyClass> anotherPtr = std::make_shared<MyClass>();
someFunction(anotherPtr);
// 手动释放 shared_ptr 对象
ptr.reset(); // 释放 ptr 指向的内存,并将 ptr 置为空指针
return 0;
}
在上面的示例中,'shared_ptr' 的构造函数接受一个指针作为参数,用于动态分配内存和管理该内存。当 'shared_ptr' 对象不再使用时(例如超出作用域或手动调用 'reset()'),它会自动调用析构函数来释放内存。
需要注意的是,'shared_ptr' 可以通过 'reset()' 函数手动释放对象。另外,当所有指向同一块内存的 'shared_ptr' 都被释放时,内存将被自动释放。
原文地址: https://www.cveoy.top/t/topic/92X 著作权归作者所有。请勿转载和采集!