C++ smart pointers are integrated into STL to facilitate pointer management and avoid memory problems. STL contains four smart pointer types: std::unique_ptr: points to a uniquely owned object std::shared_ptr: points to a multiple-owned object std::weak_ptr: points to a weak reference to a potentially invalid object std::auto_ptr (deprecated)
Smart pointers in C++ are designed to simplify pointer management and avoid problems such as memory leaks and dangling pointers. For ease of use, smart pointers have been integrated into the Standard Template Library (STL).
There are four types of smart pointers in STL:
std::unique_ptr
: Points to a uniquely owned objectstd::shared_ptr
: Points to a multi-ownership object std::weak_ptr
: Points to a weak reference to a potentially invalid objectstd::auto_ptr
: Deprecated, deprecatedSmart pointers are integrated into STL, which means you can target any STL containers use them. For example:
// 使用 unique_ptr 存储整数 std::vector<std::unique_ptr<int>> int_ptrs; // 使用 shared_ptr 存储字符串 std::list<std::shared_ptr<std::string>> str_ptrs;
Suppose we want to create a container containing a file path. We can use smart pointers to ensure that the file path object is not accidentally destroyed during the lifetime of the container.
#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<std::unique_ptr<FilePath>> 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 << file_path->path_ << std::endl; } return 0; }
This code uses std::unique_ptr
to manage FilePath
objects. When the container goes out of scope, the smart pointer will automatically destroy the object it points to, ensuring no memory leaks.
The above is the detailed content of How are C++ smart pointers integrated into the Standard Template Library (STL)?. For more information, please follow other related articles on the PHP Chinese website!