简体   繁体   English

模板中的智能指针 c++

[英]Smart Pointers in templates c++

Create a class template SmartPointer that should contain a pointer to any object and delete that same object when the destructor of that class is called.创建一个 class 模板SmartPointer ,该模板应包含指向任何 object 的指针,并在调用 ZA2F2ED4F8EBC0ABC1CDC4 的析构函数时删除相同的 object。 In order for the smart pointer to behave the same way the raw pointer behaves, you must overlap the operator * and -> .为了使智能指针的行为与原始指针的行为相同,您必须重叠运算符*->

So, this is my task, and I've done this code, but the -> operator is not okay.所以,这是我的任务,我已经完成了这段代码,但是->运算符不行。 If someone knows how to fix it, please help me.如果有人知道如何解决它,请帮助我。

template <class T>
class SmartPointer {
private:
    T* x;
public:
    T& operator*() {
        return *x;
    }
    T& operator->(){
        return this();
    }
    SmartPointer(T *X);
    ~SmartPointer();
};

template<class T>
SmartPointer<T>::SmartPointer(T *X) {
    this->x = X;
}

template<class T>
SmartPointer<T>::~SmartPointer() {
    delete x;
}

The operator-> function should return a pointer . operator-> function 应该返回一个指针 And it should be a pointer to the wrapped object:它应该是一个指向包装好的 object 的指针:

T* operator->()
{
    return x;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM