C++ 智能指针

以前一直知道自己C++弱,但是何曾想.....竟然弱到让人心碎....  就是当是补当时莉莉的作业吧!

参考博客:JustDoIT

C++的智能指针有四种,auto_ptr, shared_ptr, weak_ptr, unique_ptr,第一个已经被C++11废掉了

使用智能指针,是为了C++的内存泄漏问题。一般new一个对象,一般不能避免代码未执行到delete时,程序就跳转出去了,挥着函数没有执行到delete就返回了,如果不在每一个可能跳转的地方或者返回的语句前释放内存,就会造成内存泄漏。使用智能指针,是因为智能指针就是一个类,当超出类的作用域时,类就会自动调用析构函数,析构函数会自动释放内存资源。

auto_ptr:主要是为了解决“有异常抛出时发生内存泄漏”的问题。如下的简单代码是这类问题的一个简单示例。

#include <iostream>
#include <string.h>
#include <memory>
using namespace std;

class Test
{
public:
    Test(string s)
    {
       str = s;
       std::cout<<"creat test
";
    }
    ~Test()
    {
            std::cout<<"delete test: "<<str<<std::endl;
    }
    string& getStr()
    {
        return str;
    }
    void setStr(string s)
    {
        str = s;
    }
    void print()
    {
            std::cout<<str<<std::endl;
    }
private:
    string str;
};
 
 
int main()
{
    std::auto_ptr<Test> ptest(new Test("123"));
    ptest->setStr("hello ");
    ptest->print();
    ptest.get()->print();
    ptest->getStr() += "world !";
    (*ptest).print();
    ptest.reset(new Test("123"));
    ptest->print();
    return 0;
}

  运行结果:

原文地址:https://www.cnblogs.com/chenyang920/p/9622207.html