c++智能指针

当在C++中处理动态内存分配时,使用智能指针是一种良好的实践,可以帮助避免内存泄漏和悬空指针等问题。C++11引入了三种主要的智能指针:std::unique_ptr、std::shared_ptr和std::weak_ptr。下面是一个简单的代码演示,展示如何使用std::unique_ptr和std::shared_ptr:

#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass(int val) : value(val) {
        std::cout << "Constructor called. Value: " << value << std::endl;
    }

    ~MyClass() {
        std::cout << "Destructor called. Value: " << value << std::endl;
    }

    void setValue(int val) {
        value = val;
    }

    int getValue() const {
        return value;
    }

private:
    int value;
};

int main() {
    // 使用 std::unique_ptr
    std::unique_ptr<MyClass> uniquePtr(new MyClass(42));
    uniquePtr->setValue(100);
    std::cout << "Value using unique_ptr: " << uniquePtr->getValue() << std::endl;

    // 使用 std::shared_ptr
    std::shared_ptr<MyClass> sharedPtr = std::make_shared<MyClass>(10);
    sharedPtr->setValue(200);
    std::cout << "Value using shared_ptr: " << sharedPtr->getValue() << std::endl;

    // shared_ptr 的引用计数
    std::cout << "shared_ptr use count: " << sharedPtr.use_count() << std::endl;

    // shared_ptr 的复制
    std::shared_ptr<MyClass> sharedPtr2 = sharedPtr;
    std::cout << "shared_ptr use count after copy: " << sharedPtr.use_count() << std::endl;

    std::weak_ptr<MyClass> weakPtr = sharedPtr;
    if (auto shared = weakPtr.lock()) {
        std::cout << "Value using weak_ptr: " << shared->getValue() << std::endl;
    } else {
        std::cout << "Object no longer exists" << std::endl;
    }

    sharedPtr.reset();

    if (auto shared = weakPtr.lock()) {
        std::cout << "Value using weak_ptr after shared_ptr reset: " << shared->getValue() << std::endl;
    } else {
        std::cout << "Object no longer exists" << std::endl;
    }

    return 0;
    return 0;
}

在这个示例中,我们创建了一个简单

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值