weak_ptr C++代码
时间: 2023-07-10 14:15:33 浏览: 56
下面是一个使用`weak_ptr`的示例代码:
```c++
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called." << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called." << std::endl;
}
};
int main() {
std::weak_ptr<MyClass> weakPtr;
{
std::shared_ptr<MyClass> sharedPtr = std::make_shared<MyClass>();
weakPtr = sharedPtr;
std::cout << "weakPtr.use_count() = " << weakPtr.use_count() << std::endl;
}
std::cout << "weakPtr.use_count() = " << weakPtr.use_count() << std::endl;
if (!weakPtr.expired()) {
std::shared_ptr<MyClass> sharedPtr = weakPtr.lock();
if (sharedPtr) {
std::cout << "weakPtr is valid." << std::endl;
} else {
std::cout << "weakPtr is invalid." << std::endl;
}
} else {
std::cout << "weakPtr is expired." << std::endl;
}
return 0;
}
```
该程序定义了一个名为`MyClass`的类,并在`main`函数中创建了一个`shared_ptr`和一个`weak_ptr`,并将它们指向`MyClass`类的一个对象。在创建`shared_ptr`之后,我们可以通过`use_count`方法查看引用计数的值,可以看到这个值为1。然后,我们在`shared_ptr`的作用域之外输出该值,我们可以看到这个值变成了0,因为`shared_ptr`已经被销毁了。接着,我们使用`expired`方法检查`weak_ptr`是否过期。如果`weak_ptr`没有过期,我们使用`lock`方法获取一个`shared_ptr`,并检查该`shared_ptr`是否为空。最后,我们输出相应的消息来指示`weak_ptr`是否有效。