使用智能指针存入容器可自动管理动态对象生命周期,避免内存泄漏。①std::unique_ptr适用于独占场景,通过移动语义高效插入容器;②std::shared_ptr支持共享所有权,适合多容器或异步任务共享对象;③优先选用unique_ptr,性能更优,避免循环引用需用weak_ptr辅助。

在C++中使用智能指针与容器结合,可以有效管理动态分配对象的生命周期,避免内存泄漏。尤其是在存储多态类型或需要动态创建对象时,智能指针配合标准容器(如
std::vector
std::list
直接在容器中保存原始指针容易导致以下问题:
使用
std::unique_ptr
std::shared_ptr
std::unique_ptr
立即学习“C++免费学习笔记(深入)”;
示例:
#include <vector>
#include <memory>
#include <iostream>
class Animal {
public:
virtual ~Animal() = default;
virtual void speak() const = 0;
};
class Dog : public Animal {
public:
void speak() const override { std::cout << "Woof!\n"; }
};
class Cat : public Animal {
public:
void speak() const override { std::cout << "Meow!\n"; }
};
int main() {
std::vector<std::unique_ptr<Animal>> animals;
animals.push_back(std::make_unique<Dog>());
animals.push_back(std::make_unique<Cat>());
for (const auto& animal : animals) {
animal->speak();
}
return 0; // 所有对象自动析构
}
注意:
std::unique_ptr
push_back
当多个部分需要共享同一对象时,
std::shared_ptr
适用场景包括:
示例:
std::vector<std::shared_ptr<Animal>> shared_animals; auto dog = std::make_shared<Dog>(); shared_animals.push_back(dog); // 其他地方也可以持有 dog // 只有当所有 shared_ptr 离开作用域后,dog 才会被销毁
基本原则:优先使用
std::unique_ptr
std::weak_ptr
基本上就这些。智能指针加容器的组合,让C++资源管理既灵活又安全。
以上就是C++智能指针在容器存储中的应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号