过度使用智能指针的意思:在不需要自动管理资源的情况下滥用智能指针,比如对于栈上分配的对象或静态分配的资源使用智能指针。对比下面的例子:
案例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() {}};
上面只是列举了两个例子,总之,智能指针是强大的工具,但应当审慎使用。在设计时,需要明确每个资源的生命周期和管理责任,避免在不需要自动管理内存的情况下使用智能指针,从而保持代码的简洁性和高效性。