c++ 通过一个临时的空的智能指针(裸指针),交换两个智能指针(裸指针)的值,注意是交换值!!!!

#include <iostream>
#include <memory>
using namespace std;

struct ParenTask // 父亲
{
    string name{};
};
typedef shared_ptr<ParenTask> ParenTaskPtr;

struct SubTask : ParenTask  // 孩子
{
    int uid{};
};
typedef shared_ptr<SubTask> SubTaskPtr;


int main()
{
    SubTaskPtr sub0;
    cout << "Hello World!" << endl;
    SubTaskPtr sub1 = make_shared<SubTask>();
    sub1->uid = 1;
    sub1->name = "HuiJtao";

    SubTaskPtr sub2 = make_shared<SubTask>();
    sub0 = sub2;
    std::swap(*(sub0.get()),*(sub1.get())); // 智能指针(交换方式)
    auto uid =  sub2->uid;
    auto name =  sub2->name;

    int *c;
    int *a = new int(10);
    int *b = new int(2);
    c = a;

    std::swap(*c,*b); // 裸指针(交换方式)
    auto aa = a;
    auto bb = b;
    return 0;
}

 

posted @ 2024-02-22 23:04  雾枫  阅读(28)  评论(0)    收藏  举报