c++过度使用智能指针

过度使用智能指针的意思:在不需要自动管理资源的情况下滥用智能指针,比如对于栈上分配的对象或静态分配的资源使用智能指针。对比下面的例子:

案例1:

假设我们正在编写一个简单的程序,用于管理一个学生列表,每个学生对象包含姓名和成绩。由于学生数量固定且相对较少,我们可以直接在栈上创建学生对象数组。但是,如果我们不恰当地使用了智能指针,可能会遇到以下情况:

使用智能指针的例子

 

#include <iostream>#include <memory>#include <vector>

class Student {public:    Student(const std::string& name, int score) : name(name), score(score) {}    std::string getName() const { return name; }    int getScore() const { return score; }

private:    std::string name;    int score;};

int main() {    // 不恰当的使用:使用std::unique_ptr管理固定数量的学生对象    std::vector<std::unique_ptr<Student>> students;

    students.emplace_back(std::make_unique<Student>("Alice", 90));    students.emplace_back(std::make_unique<Student>("Bob", 85));    students.emplace_back(std::make_unique<Student>("Charlie", 95));

    for(const auto& studentPtr : students) {        std::cout << "Name: " << studentPtr->getName() << ", Score: " << studentPtr->getScore() << std::endl;    }

    return 0;}

 

改善的做法

 

#include <iostream>#include <vector>

class Student {public:    Student(const std::string& name, int score) : name(name), score(score) {}    std::string getName() const { return name; }    int getScore() const { return score; }

private:    std::string name;    int score;};

int main() {    // 更合适的方式:直接在栈上创建学生对象    std::vector<Student> students = {        {"Alice", 90},        {"Bob", 85},        {"Charlie", 95}    };

    for(const auto& student : students) {        std::cout << "Name: " << student.getName() << ", Score: " << student.getScore() << std::endl;    }

    return 0;}

 

案例2:静态分配或者单例模式的过度包装

 

class Singleton {public:    static std::shared_ptr<Singleton> getInstance() {        static std::shared_ptr<Singleton> instance = std::make_shared<Singleton>();        return instance;    }private:    Singleton() {}};

改善后的代码

 

class Singleton {public:    static Singleton& getInstance() {        static Singleton instance;        return instance;    }private:    Singleton() {}};

 

上面只是列举了两个例子,总之,智能指针是强大的工具,但应当审慎使用。在设计时,需要明确每个资源的生命周期和管理责任,避免在不需要自动管理内存的情况下使用智能指针,从而保持代码的简洁性和高效性。

 

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值