题解 | #智能指针的使用#

智能指针的使用

https://www.nowcoder.com/practice/fea3ca1e4d384a5a80290f1cec138078

#include <cstddef>
#include <iostream>
using namespace std;

template <class T>
class SharedPtr {
private:
    T* _ptr{nullptr};
    size_t* _cnt{nullptr};
public:
    SharedPtr() = default;
    explicit SharedPtr(T* p) : _ptr(p), _cnt(new size_t(p ? 1 : 0)) {}
    SharedPtr(const SharedPtr& other) : _ptr(other._ptr), _cnt(other._cnt) {
        if (_ptr) ++(*_cnt);
    }

    SharedPtr& operator=(const SharedPtr& other) {
        if (this != &other) {
            if (_ptr && --(*_cnt) == 0) {
                delete _ptr;
                delete _cnt;
            }
            _ptr = other._ptr;
            _cnt = other._cnt;
            if (_ptr) ++(*_cnt);
        }
        return *this;
    }

    ~SharedPtr() {
        if (_ptr && --(*_cnt) == 0) {
            delete _ptr;
            delete _cnt;
        }
    }
    size_t useCnt() const {return _cnt ? *_cnt : 0;}
    T* get() const {return _ptr;}
    T* operator->() const {return _ptr;}
    T& operator*() const {return *_ptr;}
};



class Student {
private:
    int _id;
    int _age;
public:
    Student() = default;
    Student(int id, int age) : _id(id), _age(age) {}
    int getId() const {
        return _id;
    }
    int getAge() const {
        return _age;
    }
};

void print(const SharedPtr<Student>& stu) {
    cout << stu->getId() << " " << stu->getAge() << " " << stu.useCnt() << endl;
}

int main() {
    int t;
    cin >> t;
    int n;
    cin >> n;
    string operation;
    SharedPtr<Student> sp;
    for (int j = 0; j < t; j ++) {
        for (int i = 0; i < n; i++) {
            cin >> operation;
            if (operation == "new") {
                int id, age;
                cin >> id >> age;
                sp = SharedPtr<Student>(new Student(id, age));
            } else if (operation == "copy") {sp = SharedPtr<Student>(sp);} 
            else if (operation == "print") {print(sp);}
        }
    }
    return 0;
}

全部评论

相关推荐

11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务