C++智能指针

在下面的例子中,当异常抛出时,Resource没有被回收,出现指针泄漏

void someFunction()
{
    Resource *ptr = new Resource;
 
    int x;
    std::cout << "Enter an integer: ";
    std::cin >> x;
 
    if (x == 0)
        throw 0; // the function returns early, and ptr won’t be deleted!
 
    // do stuff with ptr here
 
    delete ptr;
}

在说智能指针之前,不得不说RAII(Resource Acquisition is Initialization),需要满足下面三个条件
1)The resource is relinquished in the destructor
2)Instances of the class are stack allocated
3)The resource is acquired in the constructor. This part is optional, but common.

class Simple
{
private:
    int m_nID;
 
public:
    Simple(int nID)
    {
        std::cout << "Constructing Simple " << nID << '\n';
        m_nID = nID;
    }
 
    ~Simple()
    {
        std::cout << "Destructing Simple" << m_nID << '\n';
    }
 
    int getID() { return m_nID; }
};
 
int main()
{
    // Allocate a Simple on the stack
    Simple simple(1);
    std::cout << simple.getID() << '\n';
 
    // Allocate a Simple dynamically
    Simple *pSimple = new Simple(2);
    std::cout << pSimple->getID() << '\n';
    delete pSimple;
 
    return 0;
} // simple goes out

执行输出如下:

Constructing Simple 1
1
Constructing Simple 2
2
Destructing Simple 2
Destructing Simple 1

根据这个特点,我们初步实现一个智能指针

#include <iostream>
 
template<class T>
class Auto_ptr1
{
    T* m_ptr;
public:
    // Pass in a pointer to "own" via the constructor
    Auto_ptr1(T* ptr=nullptr)
        :m_ptr(ptr)
    {
    }
    
    // The destructor will make sure it gets deallocated
    ~Auto_ptr1()
    {
        delete m_ptr;
    }
 
    // Overload dereference and operator-> so we can use Auto_ptr1 like m_ptr.
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
};
 
// A sample class to prove the above works
class Resource
{
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};
 
int main()
{
    Auto_ptr1<Resource> res(new Resource); // Note the allocation of memory here
 
        // ... but no explicit delete needed
 
    // Also note that the Resource in angled braces doesn't need a * symbol, since that's supplied by the template
 
    return 0;
} // res goes out of scope here, and destroys the allocated Resource for us

输出如下:

Resource acquired
Resource destroyed

对于复杂的情况,上面的就无法处理,比如

#include <iostream>
 
// Same as above
template<class T>
class Auto_ptr1
{
    T* m_ptr;
public:
    Auto_ptr1(T* ptr=nullptr)
        :m_ptr(ptr)
    {
    }
    
    ~Auto_ptr1()
    {
        delete m_ptr;
    }
 
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
};
 
class Resource
{
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};
 
int main()
{
    Auto_ptr1<Resource> res1(new Resource);
    Auto_ptr1<Resource> res2(res1); // Alternatively, don't initialize res2 and then assign res2 = res1;
 
    return 0;
}

输出:

Resource acquired
Resource destroyed
Resource destroyed

我们可以扩展如下

#include <iostream>
 
template<class T>
class Auto_ptr2
{
    T* m_ptr;
public:
    Auto_ptr2(T* ptr=nullptr)
        :m_ptr(ptr)
    {
    }
    
    ~Auto_ptr2()
    {
        delete m_ptr;
    }
 
    // A copy constructor that implements move semantics
    Auto_ptr2(Auto_ptr2& a) // note: not const
    {
        m_ptr = a.m_ptr; // transfer our dumb pointer from the source to our local object
        a.m_ptr = nullptr; // make sure the source no longer owns the pointer
    }
    
    // An assignment operator that implements move semantics
    Auto_ptr2& operator=(Auto_ptr2& a) // note: not const
    {
        if (&a == this)
            return *this;
 
        delete m_ptr; // make sure we deallocate any pointer the destination is already holding first
        m_ptr = a.m_ptr; // then transfer our dumb pointer from the source to the local object
        a.m_ptr = nullptr; // make sure the source no longer owns the pointer
        return *this;
    }
 
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
    bool isNull() const { return m_ptr == nullptr;  }
};
 
class Resource
{
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};
 
int main()
{
    Auto_ptr2<Resource> res1(new Resource);
    Auto_ptr2<Resource> res2; // Start as nullptr
 
    std::cout << "res1 is " << (res1.isNull() ? "null\n" : "not null\n");
    std::cout << "res2 is " << (res2.isNull() ? "null\n" : "not null\n");
 
    res2 = res1; // res2 assumes ownership, res1 is set to null
 
    std::cout << "Ownership transferred\n";
 
    std::cout << "res1 is " << (res1.isNull() ? "null\n" : "not null\n");
    std::cout << "res2 is " << (res2.isNull() ? "null\n" : "not null\n");
 
    return 0;
}

输出:

Resource acquired
res1 is not null
res2 is null
Ownership transferred
res1 is null
res2 is not null
Resource destroyed
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 文:心阳 今夜我是一颗 迷途的星星 失足坠入了你的梦 无风也瑟瑟发抖 / 那无边的孤独 你看见了吗? 在你抬头之处...
    LT心阳阅读 1,460评论 34 44
  • 2017年已经过去101天。我很慢,我愿意等我。 越来越珍视自己的时间了。 朋友约玩,会想要花费多少时间,是否有成...
    夏欧阅读 553评论 0 51
  • “不”就是一个字,有时,当你遇上一些事情的时候,你强大,你会说“不”,可如果你懦弱呢?(我也是)不敢说“不”呢? ...
    百合花王梓诺阅读 266评论 0 1

友情链接更多精彩内容