unique_ptr、memcpy等一些实现

面试让我手撕unique_ptr,被吓怕了,记录一些偏底层的实现或者一些可能让手撕的比较偏的函数

  1. unique_ptr实现
  2. memcpy实现—注意地址重叠
  3. 重写构造函数与赋值函数—有指针类型时,防止重复释放内存
  4. 可变参数模板
  5. i++,++i
  6. shared_ptr死锁情况
  7. 单例模式
  8. 工厂模式(简单工厂模式、工厂模式、抽象工厂模式)
  9. 环形队列(二倍扩容)
  10. shared_ptr实现
  11. strcpy实现

unique_ptr实现

#include <iostream>
using namespace std;
template<class T>
class Unique_ptr
{
private:
    T* ptr=NULL;
public:
    Unique_ptr(Unique_ptr& u) = delete;
    Unique_ptr& operator=(Unique_ptr& u) = delete;
    Unique_ptr(T* p)
    {
        ptr = p;
        cout << "构造" << endl;
    }
    Unique_ptr()
    {
    }
    ~Unique_ptr()
    {
        if (ptr)
        {
            delete ptr;
            ptr = NULL;
            cout << "析构" << endl;
        }
    }
    Unique_ptr(Unique_ptr&& p)
    {
        ptr = p.ptr;
        p.ptr = NULL;
    }
    Unique_ptr& operator=(Unique_ptr&& p)
    {
        if(this!=&p){
            ptr = p.ptr;
            p.ptr = NULL;
        }
        return *this;
    }
    T* operator->()
    {
        return ptr;
    }
    T& operator*()
    {
        if (ptr)
        {
            return *ptr;
        }
        T a = -1;
        return a;
    }
	
};
int main()
{
    int* a = new int(10);
    Unique_ptr<int> p(a);
    cout << *p << endl;
    Unique_ptr<int> p1=move(p);
    cout << *p1 << endl;
    cout << *p << endl; 
}

memcpy实现—注意地址重叠

#include <iostream>
using namespace std;
template <class T>
T* my_memcpy(T* dst, T* src, int size_s)
{
    if (sizeof(dst) < size_s)
    {
        return NULL;
    }
    if (dst == NULL || src == NULL)
    {
        return NULL;
    }
    if (src < dst && (src + size_s > dst))
    {
        T* d = dst + size_s - 1;
        T* s = src + size_s - 1;
        while (size_s--)
        {
            *d = *s;
            d--;
            s--;
        }
    }
    else
    {
        T* d = dst;
        T* s = src;
        while (size_s--)
        {
            *d = *s;
            d++;
            s++;
        }
    }
    return dst;
}
int main()
{
    char buf[5] = "abcd";
    char buf1[4];
   // memcpy(buf + 2, buf, 5);
    cout << sizeof(buf1);
    char* res=my_memcpy<char>(buf1, buf, 5);
    if (res == NULL)
    {
        cout << 0;
        return 0;
    }
    for (int i = 0; i < strlen(res); i++)
    {
        cout << res[i];
    }

}

重写构造函数与赋值函数—有指针类型时,防止重复释放内存

#include <iostream>
using namespace std;
class base
{
private:
    int id;
    int* ptr;
public:
    base(int a, int* d)
    {
        id = a;
        ptr = new int;
        if (d)
        {
            *ptr = *d;
        }
    }
    ~base()
    {
        if (ptr)
        {
            delete ptr;
            ptr = NULL;
            cout << "析构" << endl;
        }  
    }
    base(const base& b)
    {
        id = b.id;
        ptr = new int;
        if (b.ptr)
        {
            *ptr = *(b.ptr);
        }
    }
    base& operator=(const base& b)
    {
        id = b.id;
        ptr= new int;
        if (b.ptr)
        {
            *ptr = *(b.ptr);
        }
        return *this;
    }
    void get()
    {
        cout << id << " " << *ptr << endl;
    }

};
int main()
{
    int* a = new int(10);
    base b(2, a);
    base c(b);
    base d = c;
    b.get() ;
    c.get();
    d.get();
}

可变参数模板

#include <iostream>
using namespace std;
template <typename T>
void foo( T& t)
{
    cout << t<<endl;
}
template<class T,class ...Arg>
void foo(T i,Arg ...t)
{
    cout << i << endl;
    foo(t...);
}
int main()
{
    foo(1,2,3,4);
    std::cout << "Hello World!\n";
}

i++,++i

int& int::operator++() //这里返回的是一个引用形式,就是说函数返回值也可以作为一个左值使用。 ++i
{//函数本身无参,意味着是在自身空间内增加1的
    *this += 1;  // 增加
    return *this;  // 取回值
}
const int int::operator++(int) //函数返回值是一个非左值型的,与前缀形式的差别所在。 i++
{//函数带参,说明有另外的空间开辟
    int oldValue = *this;  // 取回值
    ++(*this);  // 增加
    return oldValue;  // 返回被取回的值
}

shared_ptr死锁情况

#include <iostream>
using namespace std;
class B; 
class A 
{
public:
    shared_ptr<B>_pb;
    A()
    {
        cout << "A构造" << endl;
    }
    ~A()
    {
        cout << "A析构" << endl;
    }
};
     
class B
{
public:
    shared_ptr<A>_pa;
    B()
    {
        cout << "B构造" << endl;
    }
    ~B()
    {
        cout << "B析构" << endl;
    }
};
void fun()
{
    shared_ptr<A> pa(new A);
    shared_ptr<B> pb(new B); 
    pa->_pb = pb;
    pb->_pa = pa;
    cout << pa.use_count()<< endl;
}
   
int main()
{
    fun();
    return 0;
}

单例模式

#include <iostream>
using namespace std;
//懒汉式(线程不安全)
class Single
{
private:
    Single() {};
    Single& operator=(Single& s) = delete;
    Single(Single& s) = delete;
    static Single *s;
public:
    ~Single() {};
    static Single* get()
    {
        if (s==nullptr)
        {
            s = new Single;
        }
        return s;
    }
};
Single* Single::s = NULL;

//饿汉式(线程安全)
class singleton_e {
private:
    singleton_e() {}
    singleton_e(const singleton_e&) = delete;
    singleton_e& operator=(const singleton_e&) = delete;
    static singleton_e* p;
public:
    static singleton_e* instance() {
        return p;
    }
    int a;
};
singleton_e* singleton_e::p = new singleton_e();

//使用局部静态变量
class Singleton_s
{
public:
    ~Singleton_s() {};
    Singleton_s(const Singleton_s&) = delete;
    Singleton_s& operator=(const Singleton_s&) = delete;
    static Singleton_s& get_instance() {  //要返回引用
        static Singleton_s instance;
        return instance;
    }
private:
    Singleton_s() {
        std::cout << "constructor called!" << std::endl;
    }
};

工厂模式(简单工厂模式、工厂模式、抽象工厂模式)

简单工厂模式

#include <iostream>
using namespace std;
class Product
{
public:
    virtual void show() = 0;
};

class Product_A : public Product
{
public:
    void show()
    {
        cout << "Product_A" << endl;
    }
};

class Product_B : public Product
{
public:
    void show()
    {
        cout << "Product_B" << endl;
    }
};

class Factory
{
public:
    Product* Create(int i)
    {
        switch (i)
        {
        case 1:
            return new Product_A;
            break;
        case 2:
            return new Product_B;
            break;
        default:
            break;
        }
    }
};

int main()
{
    Factory* factory = new Factory();
    factory->Create(1)->show();
    factory->Create(2)->show();
    system("pause");
    return 0;
}

工厂模式

#include <iostream>
using namespace std;
class Product
{
public:
    virtual void show() = 0;
};
class Product_A : public Product
{
public:
    void show()
    {
        cout << "Product_A" << endl;
    }
};
class Product_B : public Product
{
public:
    void show()
    {
        cout << "Product_B" << endl;
    }
};
class Factory
{
public:
    virtual Product* create() = 0;
};

class Factory_A : public Factory
{
public:
    Product* create()
    {
        return new Product_A;
    }
};

class Factory_B : public Factory
{
public:
    Product* create()
    {
        return new Product_B;
    }
};

int main()
{
    Factory_A* productA = new Factory_A();
    Factory_B* productB = new Factory_B();

    productA->create()->show();
    productB->create()->show();
    system("pause");
    return 0;
}

抽象工厂模式

#include <iostream>
using namespace std;
class product1
{
public:
    virtual void show() = 0;
};

//定义具体类
class product_A1 :public product1
{
public:
    void show() { cout << "product A1" << endl; }
};

class product_B1 :public product1
{
public:
    void show() { cout << "product B1" << endl; }
};

//定义抽象类
class product2
{
public:
    virtual void show() = 0;
};

//定义具体类
class product_A2 :public product2
{
public:
    void show() { cout << "product A2" << endl; }
};

class product_B2 :public product2
{
public:
    void show() { cout << "product B2" << endl; }
};


class Factory
{
public:
    virtual product1* creat1() = 0;
    virtual product2* creat2() = 0;
};

class FactoryA
{
public:
    product1* creat1() { return new product_A1(); }
    product2* creat2() { return new product_A2(); }
};

class FactoryB
{
public:
    product1* creat1() { return new product_B1(); }
    product2* creat2() { return new product_B2(); }
};

int main()
{
    FactoryA* factoryA = new FactoryA();
    factoryA->creat1()->show();
    factoryA->creat2()->show();

    FactoryB* factoryB = new FactoryB();
    factoryB->creat1()->show();
    factoryB->creat2()->show();

    return 0;
}

环形队列(二倍扩容)

class CircleQueue
{
public:
	CircleQueue(int size = 20);
	~CircleQueue();
	CircleQueue(const CircleQueue& src);
	void operator =(const CircleQueue& src);
	void push(int val);
	void pop();
	int front();
	int back();
	bool empty();
	bool full();
private:
	int* _pQue;
	int _size;
	int _front;
	int _rear;
	void resize();
};

CircleQueue::CircleQueue(int size)
{
	_pQue = new int[size];
	memset(_pQue, 0, sizeof(int) * size);
	_size = size;
	_front = 0;
	_rear = 0;
}
CircleQueue::~CircleQueue()
{
	delete[] _pQue;
	_pQue = NULL;
}
CircleQueue::CircleQueue(const CircleQueue& src)
{
	_pQue = new int[src._size];
	memset(_pQue, 0, sizeof(int) * src._size);
	_size = src._size;
	_front = src._front;
	_rear = src._rear;
}
void CircleQueue::operator=(const CircleQueue& src)
{
	if (this == &src)
		return;

	delete[]_pQue;//通用做法,如果内存容量足够,直接使用

	_pQue = new int[src._size];
	memset(_pQue, 0, sizeof(int) * src._size);
	_size = src._size;
	_front = src._front;
	_rear = src._rear;
	for (int i = _front; i < _rear; i = (i + 1) % _size)
	{
		_pQue[i] = src._pQue[i];
	}
}
void CircleQueue::push(int val)
{
	if (full())
		resize();
	_pQue[_rear] = val;
	_rear = (_rear + 1) % _size;
}
void CircleQueue::pop()
{
	if (empty())
		return;
	_front = (_front + 1) % _size;
}
int CircleQueue::front()
{
	return _pQue[_front];
}
int CircleQueue::back()
{
	return _pQue[_rear - 1];
}
bool CircleQueue::empty()
{
	return _rear == _front;
}
bool CircleQueue::full()
{
	return (_rear + 1) % _size == _front;//牺牲一元素空间判满
}
void CircleQueue::resize()
{
	int* tmp = new int[_size * 2];
	int count = 0;
	memset(tmp, 0, sizeof(int) * _size * 2);
	for (int i = _front; i < _rear; i = (i + 1) % _size)
	{
		tmp[count++] = _pQue[i];
	}
	_front = 0;
	_rear = count;
	_size *= 2;
	delete[]_pQue;
	_pQue = tmp;
}

shared_ptr实现

// 14.shared_ptr.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <iostream>
using namespace std;
template <typename T>
class myshared_ptr
{
public:
	myshared_ptr(T* value) //:ptr(value), count(new int(1))
	{
		ptr = value;
		count++;
	}
	myshared_ptr(const myshared_ptr& m)
	{
		ptr = m.ptr;
		count = m.count;
		count++;
	}
	myshared_ptr& operator=(const myshared_ptr& m)
	{
		if (this != &m)
		{
			ptr = m.ptr;
			count = m.count;
			count++;
		}
		return *this;
	}
	T& operator->()
	{
		return this->ptr;
	}
	~myshared_ptr()
	{
		count--;
		if (this->count== 0)
		{
			delete ptr;
			//delete count;
			//ptr = nullptr;
			//count = nullptr;
			cout << "释放内存空间" << endl;
		}
	}
public:
	T* ptr;
	static int count;
};
template <typename T>
int myshared_ptr<T>::count = 0;

void testshared_ptr()
{
	myshared_ptr<int> res(new int(2));
	cout << (res.count) << endl;
	myshared_ptr<int> res2(res);
	cout << (res2.count) << endl;
	myshared_ptr<int> res3 = res;
	cout << (res.count) << endl;
	cout << (res2.count) << endl;
	cout << (res3.count) << endl;
	res.~myshared_ptr();
	cout << (res3.count) << endl;
	res2.~myshared_ptr();
	cout << (res3.count) << endl;
	res3.~myshared_ptr();
}

int main()
{
	testshared_ptr();
}

strcpy实现

#include <iostream>
#pragma warning(disable:4996)
char* Mystrcpy(char* dest, const char* src)
{
	if (dest == NULL || src == NULL)
	{
		return NULL;
	}
	char* tmp = dest;
	while (*src != '\0')
	{
		*dest = *src;
		dest++;
		src++;
	}
	*dest = *src;
	return tmp;
}
int main()
{
	char arr1[10] = "abcdef";
	char arr2[] = "123";
	char* p = Mystrcpy(arr1, arr2);
	printf("%s", p);
	
	return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值