C++智能指针unique_ptr学习笔记

  1. C++11特性里面引入了很多智能指针,其中就包括unique_ptr,智能指针的作用是管理一个指针以防止指针忘记释放而造成内存泄露。
  2. unique_ptr是一个类,当超出了类的作用域,类会自动调用析构函数,析构函数会自动释放资源。其原理就是在函数结束时自动释放内存空间。
  3. unique_ptr的头文件为memory
#include<iostream>
#include<memory>
using namespace std;
class Dog{

    public:
        Dog(){
            cout<<"Nameless dog created."<<endl;
            s1="nameless";

        }
        Dog(string name){
            cout<<"Dog is created:" << name<<endl;
            s1=name;

        }
        void foo(){

            cout<<"Dog "<<s1<<" rules. "<<endl;

        }
        ~Dog(){
            cout<<"Dog is destoryed:"<<s1<<endl;
        }
    private:
        string s1;

};
void test()
{
    unique_ptr<Dog> pd(new Dog("jinmao"));
    pd->foo();
}
int main()
{
    test();
    return 0;
}

无法同时用多个智能指针指向同一个对象,如下程序报错

#include<iostream>
#include<memory>
using namespace std;
class Dog{

    public:
        Dog(){
            cout<<"Nameless dog created."<<endl;
            s1="nameless";

        }
        Dog(string name){
            cout<<"Dog is created:" << name<<endl;
            s1=name;

        }
        void foo(){

            cout<<"Dog "<<s1<<" rules. "<<endl;

        }
        ~Dog(){
            cout<<"Dog is destoryed:"<<s1<<endl;
        }
    private:
        string s1;

};
void test()
{
    unique_ptr<Dog> pd(new Dog("jinmao"));
    unique_ptr<Dog> pd1;
    pd1=pd;//程序报错,应该保证同一时间内只有一个智能指针可以指向该对象
  
}
int main()
{
    test();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值