自我/自己实现智能指针

问题描述 投票:-3回答:1

我正在尝试编写自己的共享指针实现(为了好玩/挑战),但是在我无法使构造函数接受任何(自动)类型的指针变量之后,我遇到了死胡同。问题是,现在我只能让我自己的智能指针指向某个数据类型(类P)但我希望它能够指向任何数据类型但是问题是我需要指定数据类型构造函数参数。

码:

    #include <iostream>
    #include <memory>

    class P //dummy class
    {
        int x;
    public:
        P() : x(42) {}
        ~P() {}

        void print()
        {
            std::cout<<"Address = "<< this << "\n";
        }
    };

    class P2 //dummy class 2
    {
    public:
        P2() {}
        ~P2() {}

        void print()
        {
            std::cout<<"Address = "<< this << "\n";
        }
    };

    class SmartP
    {

        P *ptr;
    public:

        SmartP(P *p) : ptr(p) {}
        ~SmartP()
        {
            delete ptr;
        }

        P& operator* ()
        {
            return *ptr;
        }

        P* operator-> ()
        {    
            return ptr;
        }
    };

    void rawPointer()
    {
        P *p(new P);
        p->print();
        delete p;   //when removed, next allocated address will be different
    }

    void smartPointerOwn()
    {
        SmartP spo(SmartP(new P));
        //This should also work but currently it does not: SmartP spo(SmartP(new P2));
        spo->print();
        //Do not need a delete
    }

    void smartPointer()
    {
        std::unique_ptr<P> sp(new P);
        sp->print();
        //Do not need a delete
    }

    int main()
    {
        rawPointer();
        smartPointerOwn();
        smartPointer();

        std::cin.get(); //Prevent exiting console prematurely
        return 0;
    }

谢谢!

c++ smart-pointers
1个回答
0
投票

这里有一些帮助你开始的基本例子。就像在评论中已经提到的那样,您应该先检查一些现有的智能指针实现。这个例子非常不完整 - 例如。缺少引用计数(如果需要共享指针)。但它给了你一个想法。我希望它有点帮助。

#include <iostream>
using namespace std;

template <typename T>
class  SmartP {
 public:
  SmartP() : p{nullptr} {}
  SmartP(T* pp) : p{pp} {}
  ~SmartP() { delete p; }

  // dereferencing operators
  friend T& operator*(const SmartP<T>& sp) { return *(sp.p); }
  T& operator->() const { return *p; }

  // get the raw pointer
  T* get() const { return p; }

 private:
  T* p;
};

int main() {

  SmartP<int> p{new int{3}};
  cout << *p << endl;

  *p = 4;
  cout << *p << endl;
}
© www.soinside.com 2019 - 2024. All rights reserved.