C++ 中使用 std::shared_ptr 存储类对象
下面是一个使用'std::shared_ptr'存储C++类对象的示例:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass(int data) : data_(data) {}
void printData() {
std::cout << 'Data: ' << data_ << std::endl;
}
private:
int data_;
};
int main() {
std::shared_ptr<MyClass> ptr(new MyClass(10));
ptr->printData(); // 输出 Data: 10
// 可以将ptr赋值给其他std::shared_ptr对象
std::shared_ptr<MyClass> ptr2 = ptr;
ptr2->printData(); // 输出 Data: 10
// 使用std::make_shared创建std::shared_ptr对象
std::shared_ptr<MyClass> ptr3 = std::make_shared<MyClass>(20);
ptr3->printData(); // 输出 Data: 20
// 通过reset函数释放资源
ptr.reset();
if (!ptr) {
std::cout << 'ptr is nullptr' << std::endl; // 输出 ptr is nullptr
}
return 0;
}
在上述示例中,'MyClass'是一个简单的类,具有一个'int'类型的成员变量'data_'和一个'printData'成员函数。通过使用'std::shared_ptr',可以在堆上分配'MyClass'对象,并自动管理其生命周期。可以通过'->'操作符访问'MyClass'对象的成员函数和成员变量。
在'main'函数中,我们首先创建了一个'std::shared_ptr
接下来,我们将'ptr'赋值给另一个'std::shared_ptr
使用'std::make_shared'可以更方便地创建'std::shared_ptr'对象。我们使用'std::make_shared
通过调用'ptr.reset()',我们释放了'ptr'所拥有的资源。在此之后,'ptr'不再拥有任何资源,因此其值变为'nullptr'。我们可以通过'if (!ptr)'检查'ptr'是否为空指针,输出'ptr is nullptr'。
这是一个简单的使用'std::shared_ptr'存储C++类对象的例子。'std::shared_ptr'提供了方便的资源管理功能,可以避免手动释放内存资源的麻烦,并自动处理对象的生命周期。
原文地址: https://www.cveoy.top/t/topic/bjap 著作权归作者所有。请勿转载和采集!