Design a class that behaves like a smart pointer

The best way to make a class behave like a pointer is to use a shared_ptr to manage the resources in the class.

Copying (assigning) a shared_ptr will copy (assign) the pointer pointed to by shared_ptr (it can be considered that shared_ptr has a reference counter); when no user uses the object, the shared_ptr class will release resources by itself. The advantages of smart pointers over ordinary pointers are mainly 2: 1. No need to delete manually 2. Avoid deleting a memory that is referenced by pointers (release memory at the right time)

 Solutions:

So how do you design your own class to behave like a smart pointer? It can be achieved by using reference counting, saving the counter in dynamic memory, when creating an object, allocate a new counter, and when copying (assigning) the object, the copy points to this The memory of the counter, so that both the copy and the original object point to the same counter.

 

h file

#pragma once
#include <string>
using namespace std;
class HasPtr
{
public:
    HasPtr(const string &s);
    HasPtr(const HasPtr&);
    HasPtr& operator=(const HasPtr &rhs);
    ~HasPtr();
private:
    size_t *use;
    string *pString;
};

cpp file

#include "stdafx.h"
#include "HasPtr.h"
#include <string>

HasPtr::HasPtr(const string &s=string()):pString(new string(s)),use(new size_t(1))
{

}

HasPtr::HasPtr(const HasPtr &p)
{
    pString = p.pString;
    use = p.use;
    ++*use;
}

HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
    ++*rhs.use; // Prevent yourself from copying yourself and make mistakes 
    if (--*use == 0 ) {
         delete pString;
         delete use;
    }
    pString = rhs.pString;
    use = rhs.use;
    return *this;
}

HasPtr::~HasPtr()
{
    if (--*use == 0) {
        delete pString;
        delete use;
    }
}

 

main.cpp

#include "stdafx.h"
#include "HasPtr.h"

intmain ()
{
    HasPtr p1("come here");
    HasPtr p2(p1); // copy construction 
    HasPtr p3 = p2; // copy construction 
    p3 = p2; // copy assignment 
    return  0 ;
}

 copy construction occurs in an initialized and an uninitialized variable,

Copy assignment occurs in 2 already initialized variables

Step by step debugging through breakpoints will find the running steps of each step

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325187706&siteId=291194637