C++:智能指針模板類(十六章)

  1. auto_ptr (c++98
  2. unique_ptr (c++11
  3. shared_ptr (c++11
    可以將new獲取的地址賦給這種對(duì)象,當(dāng)智能指針過(guò)期時(shí),其析構(gòu)函數(shù)將使用delete來(lái)釋放內(nèi)存。
  4. 頭文件:memory

shared_ptr
含有跟蹤引用特定對(duì)象的智能指針數(shù),就是可以計(jì)數(shù)有多少個(gè)ptr指向同一個(gè)地址,當(dāng)最后一個(gè)指向這個(gè)地址的ptr過(guò)期,才delete這個(gè)地址。

unique_ptr
ownership,只能有一個(gè)智能指針可以擁有特定對(duì)象。
auto_ptr也是這樣,但是auto_ptr沒(méi)那么嚴(yán)格。

auto_ptr與shared_ptr

#include<iostream>
#include<string> 
#include<memory>

int main()
{
    using namespace std;
    auto_ptr<string> films[5]=
    {
        auto_ptr<string>(new string("Fowl Balls")),
        auto_ptr<string>(new string("Duck Walks")),
        auto_ptr<string>(new string("Chicken Runs")),
        auto_ptr<string>(new string("Turkey Errors")),
        auto_ptr<string>(new string("Goose Eggs"))
    };
    
    auto_ptr<string> pwin;
    pwin = films[2];
    cout<<"Films list:\n";
    for(int i=0;i<5;i++)
        cout<<*films[i]<<endl;
    cout<<"Winner is "<<*pwin<<endl;
    return 0;
}

pwin = films[2]之后,films[2] 的所有權(quán)被pwin奪走,就是pwin指向那個(gè)地址,而films[2]變成空白字符串了

image.png

將auto_ptr換成shared_ptr
using namespace std;
    shared_ptr<string> films[5]=
    {
        shared_ptr<string>(new string("Fowl Balls")),
        shared_ptr<string>(new string("Duck Walks")),
        shared_ptr<string>(new string("Chicken Runs")),
        shared_ptr<string>(new string("Turkey Errors")),
        shared_ptr<string>(new string("Goose Eggs"))
    };
    
    shared_ptr<string> pwin;
    pwin = films[2];
    cout<<"Films list:\n";
    for(int i=0;i<5;i++)
        cout<<*films[i]<<endl;
    cout<<"Winner is "<<*pwin<<endl;
    return 0;
image.png

unique_ptr和auto_ptr

從上面例子可知,使用auto_ptr極可能會(huì)導(dǎo)致指針?biāo)傅刂返乃袡?quán)被轉(zhuǎn)到其他指針身上。unique_ptr發(fā)生這樣的情況會(huì)報(bào)錯(cuò)。
且unique_ptr還有一個(gè)特點(diǎn)就是滯后性?


image.png

這樣會(huì)報(bào)錯(cuò)。

    using namespace std;
    unique_ptr<string> s1(new string ("Hello I am"));
    unique_ptr<string> s2;
    s2 = unique_ptr<string> (new string(" Jeff"));
    unique_ptr<string> s3(new string(*s2));
    cout<<*s1<<*s2<<endl;
    cout<<*s3<<endl;
    return 0;

這樣為什么不報(bào)錯(cuò)呢,因?yàn)樗鼊?chuàng)建臨時(shí)的unique_ptr對(duì)象,然后復(fù)制給s2,臨時(shí)對(duì)象被刪除,所以沒(méi)啥問(wèn)題。

using namespace std;
unique_ptr<string> demo(const char* c);
int main()
{
    
    unique_ptr<string> s1,s2;
    s1 = demo("I love you");
    s2 = move(s1);
    s1 = demo("Honey ");
    cout<<*s1<<*s2<<endl;
    return 0;
}
unique_ptr<string> demo(const char* c)
{
    unique_ptr<string> s(new string(c));
    return s;
}

move()函數(shù)可以將一個(gè)unique_ptr賦值給另一個(gè),demo()函數(shù)的原理跟上面原理相同但是會(huì)更美化一些。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容