C++智能指针解决内存泄漏

  C#、Java、python和go等语言中都有垃圾自动回收机制,在对象失去引用的时候自动回收,而且基本上没有指针的概念,而C++语言不一样,C++充分信任程序员,让程序员自己去分配和管理堆内存,如果管理的不好,就会很容易的发生内存泄漏问题。
  C++缺点:我们知道c++的内存管理是让很多人头疼的事,当我们写一个new语句时,一般就会立即把delete语句直接也写了。

/* 智能指针可以防止内存泄漏,智能指针用法 */
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

class Test
{
public:
    Test(string s)
    {
		str = s;
		cout << "Test creat\n";
    }
    ~Test()
    {
        cout<<"Test delete:"<<str<<endl;
    }
    string & getStr()
    {
        return str;
    }
    void setStr(string s)
    {
        str = s;
    }
    void print()
    {
        cout<<str<<endl;
    }
private:
    string str;
};
 
 
int main()
{
	/* 定义类Test智能指针ptest,指向new出来的实例"123",智能指针关键字auto_ptr C++89*/
    auto_ptr<Test> ptest(new Test("123"));
    ptest->setStr("hello");
    ptest->print();
    ptest.get()->print();/*get智能指针成员方法*/
    ptest->getStr() += "world !";
    (*ptest).print();
    ptest.reset(new Test("123"));/*reset智能指针成员方法,reset释放原来资源使用权,并指向新的资源"123"*/
    ptest->print();
    return 0;
}

参考文章
c++ 智能指针用法详解

猜你喜欢

转载自blog.csdn.net/u014783785/article/details/106473610
今日推荐