c++oding="utf-8" ?>
c++ 智能指针集成到 stl 中,方便管理指针,避免内存问题。stl 包含四种智能指针类型:std::unique_ptr:指向唯一所有权对象std::shared_ptr:指向多重所有权对象std::weak_ptr:指向潜在无效对象的弱引用std::auto_ptr(已废弃)

C++ 智能指针如何集成到标准模板库 (STL) 中
C++ 中的智能指针旨在简化指针管理,避免内存泄漏和悬垂指针等问题。为了方便使用,智能指针已被集成到标准模板库 (STL) 中。
智能指针类型
STL 中有四种类型的智能指针:
-
std::unique_ptr:指向唯一所有权对象 -
std::shared_ptr:指向多重所有权对象 -
std::weak_ptr:指向潜在无效对象的弱引用 -
std::auto_ptr:已废弃,不建议使用
集成到 STL
智能指针已集成到 STL 中,这意味着您可以针对任何 STL 容器使用它们。例如:
// 使用 unique_ptr 存储整数 std::vector<:unique_ptr>> int_ptrs; // 使用 shared_ptr 存储字符串 std::list<:shared_ptr>> str_ptrs;</:shared_ptr></:unique_ptr>
实战案例
假设我们要创建一个包含文件路径的容器。我们可以使用智能指针来确保在容器的生存期内文件路径对象不会被意外销毁。
#include <vector>
#include <memory>
class FilePath {
public:
FilePath(const std::string& path) : path_(path) {}
~FilePath() = default;
private:
std::string path_;
};
int main() {
// 使用 unique_ptr 存储 FilePath 在 vector 中
std::vector<:unique_ptr>> file_paths;
file_paths.emplace_back(std::make_unique<filepath>("path/to/file1"));
file_paths.emplace_back(std::make_unique<filepath>("path/to/file2"));
// 使用 FilePath 对 vector 进行迭代,不会出现悬垂指针
for (auto& file_path : file_paths) {
std::cout path_ <p>这段代码使用 <code>std::unique_ptr</code> 来管理 <code>FilePath</code> 对象。当容器超出<a style="color:#f60; text-decoration:underline;" title="作用域" href="https://m.php.cn/zt/35787.html" target="_blank">作用域</a>时,智能指针将自动销毁所指向的对象,确保没有内存泄漏。</p></filepath></filepath></:unique_ptr></memory></vector>
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











