c++ unique_ptr和shared_ptr转换

 unique_ptr和shared_ptr

  1.  不能将shared_ptr转成unique_ptr,因为unique_ptr是独占指针
  2.  可以将unique_ptr转成shared_ptr,通过move方法

 补充:

最好将函数的返回智能指针类型设置为unique_ptr,因为可以随时转为shared_ptr,这样可以提高代码复用率。

 示例: 

复制代码
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include<Windows.h>  
using namespace std;


//自定义数据类型
class Person {
public:
    Person(string name, int age) {
        mName = name;
        mAge = age;
    }

    Person();

    ~Person()
    {
        cout << "Person 析构函数" << endl;
    }

    void Set_Name(string name)
    {
        this->mName = name;
    }

    void Info()
    {
        std::cout << "name:" << this->mName << endl;
    }

    // 在这里定义一个unique_ptr的别名UniquePtr
    using UniquePtr = unique_ptr<Person>;
public:
    string mName;
    int mAge;
}; 

unique_ptr<Person> GetUniquePtr()
{
    unique_ptr<Person> u1 = make_unique<Person>();
    u1->Set_Name("测试");
    return u1;
}

int main() {

    shared_ptr<Person> s1 = move(GetUniquePtr());
    s1->Info();
     

    cout << "s1->count=" << s1.use_count() << endl; 
    return 0;
}

Person::Person()
{
}
复制代码

 

 结果:

 

  

posted @   安静点--  阅读(1485)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
历史上的今天:
2021-12-11 页面之间跨域数据传输
点击右上角即可分享
微信分享提示