关于智能指针 [英] About smart pointers

查看:95
本文介绍了关于智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于此代码中的复制构造函数和operator = overload。我理解它但不完美。有人能解释我两个表达方式吗?在此先感谢!!!

My question is about the copy constructor and operator = overload in this code. I uderstand it but not perfectly. Can someone explain me that two expressions? Thanks in advance!!!

#include <iostream>
using namespace std;

template <class T>

class Auto_ptr2{
private:
    T *m_ptr;
public:
    Auto_ptr2(T *ptr=nullptr)
    {


    }
    ~Auto_ptr2(){
    delete m_ptr;
    }
    Auto_ptr2(Auto_ptr2 &p)
    {
        m_ptr=p.m_ptr;
        p.m_ptr=nullptr;


    }
    Auto_ptr2 operator=(Auto_ptr2 &p)
    {
        if(&p==this){return *this;}
        else{
            delete m_ptr;
            m_ptr=p.m_ptr;
            return *this;

        }

    }
    T &operator*(){return *m_ptr;}
    T *operator->(){return m_ptr;}
bool isNull()const{return m_ptr==nullptr;}
};

class Resource{
public:
    Resource(){cout<<"Resource is acquired"<<endl;}
    ~Resource(){cout<<"Resource is destroyed"<<endl;}


};


int main()
{
    Auto_ptr2<Resource> res1(new Resource);
    Auto_ptr2<Resource> res2;
    cout<<"res1 is: "<<(res1.isNull()?"null":"not null")<<endl;
    cout<<"res2 is: "<<(res2.isNull()?"null": "not null")<<endl;
    res2=res1;
    cout<<"res1 is: "<<(res1.isNull()?"null":"not null")<<endl;
    cout<<"res2 is: "<<(res2.isNull()?"null": "not null")<<endl;


}





我的尝试:



我试图理解它,我现在明白了,但并不完美:)



What I have tried:

I have tried to understand it, I understand it now, but not perfectly :)

推荐答案

在copy和constructor是成员指针的赋值,它包含原始指针。但这些不仅是指针,而且还分配了必须单独处理的内存。



我会判断他们错误,通过不进行深层复制删除右侧。



我的实现

In the copy and constructor are assigments of the member pointer, which contains the raw pointer. But these arent not only pointers, but also allocated memory which must get handled seperatly.

I would judge them a wrong, by not making a deep copy but deleting the right side.

My implementation
Auto_ptr2(const Auto_ptr2 &p)
{
    m_ptr= MakeCopy( p.m_ptr );//make a full copy of object
    //p.m_ptr=nullptr;
}
Auto_ptr2 operator=(const Auto_ptr2 &p)
{
    if(&p==this){return *this;}
    else{
        delete m_ptr;//correct deleting the old raw copy
        m_ptr=MakeCopy( p.m_ptr );
        return *this;
    }
}



另一种解决方案可以是所谓的引用计数体系结构,当计数器用于控制原始指针数据的生命周期时。


Another solution can be the so called reference counting architecture, when a counter is used to controls the lifecycle of the raw pointer data.


基本上auto_ptr是在C ++之前移动所有权的尝试11.然而,该实现已知问题,因为当时的语言还没有右值引用和移动语义...



如果可能的话使用 std :: unique_ptr std :: shared_ptr
Essentially auto_ptr was an attempt to move ownership before C++ 11. However, that implementation has known problems because the language at that time didn't yet have rvalue reference and move semantic...

If possible use std::unique_ptr or std::shared_ptr.


这篇关于关于智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆