智慧指標引用計數變化學習

lypbendlf發表於2024-05-30

1.引用和複製物件

int main() { 
    shared_ptr<Person> p=make_shared<Person>();
    p->age = 5;
    cout<<"age: "<<p->age<<", use: "<<p.use_count()<<"\n\n";

    cout<<"after B. age: "<<p->age<<", use: "<<p.use_count();
    auto & p2 = p; // 引用型別
    cout<<"user_count: "<<p.use_count()<<", "<<p2.use_count()<<"\n";
    p2->age = 10;// 更改物件值
    cout<<"age: "<<p->age<<", "<<p2->age<<"\n\n";

    auto p3 = p; // 複製一個物件
    cout<<"user_count: "<<p.use_count()<<", "<<p2.use_count()<<", "<<p3.use_count()<<"\n";
    p3->age = 15;// 更改物件值
    cout<<"age: "<<p->age<<", "<<p2->age<<", "<<p3->age;
    cout<<endl;
    return 0;
}

// 執行結果:
age: 5, use: 1

after B. age: 5, use: 1user_count: 1, 1
age: 10, 10

user_count: 2, 2, 2
age: 15, 15, 15

2.作為函式傳參值和引用

// 值傳遞,仍然會改變函式外層指向物件的值
void changeValueA(shared_ptr<Person> p){
    p->age = 10;
    cout<<"In A. age: "<<p->age<<", use: "<<p.use_count()<<"\n";// 引用計數+1,仍指向原來的物件地址
}

// 引用型別
void changeValueB(shared_ptr<Person>& p){
    p->age = 15;
    cout<<"In B. age: "<<p->age<<", use: "<<p.use_count()<<"\n";
}

int main() { 
    shared_ptr<Person> p=make_shared<Person>();
    p->age = 5;
    cout<<"age: "<<p->age<<", use: "<<p.use_count()<<"\n\n";

    changeValueA(p);
    cout<<"after A. age: "<<p->age<<", use: "<<p.use_count()<<"\n\n";

    changeValueB(p);
    cout<<"after B. age: "<<p->age<<", use: "<<p.use_count();
    cout<<endl;
    return 0;
}

// 執行結果
age: 5, use: 1

In A. age: 10, use: 2
after A. age: 10, use: 1

In B. age: 15, use: 1
after B. age: 15, use: 1

相關文章