• 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;
    }
    

      运行结果:

  • 相关阅读:
    java中变量的内存分配
    类加载器的双亲委派机制
    缓存行对齐
    缓存一致性与MESI协议
    Mysql优化之join优化
    MySQL crc32 & crc64函数 提高字符串查询效率
    线程不安全
    学习爱上 systemd
    Ubuntu如何备份和恢复系统
    redis报错overcommit_memory is set to 0
  • 原文地址:https://www.cnblogs.com/chenyang920/p/9622207.html
Copyright © 2020-2023  润新知