std::unique_ptr
时间: 2023-09-08 10:13:28 浏览: 50
std::unique_ptr is a smart pointer template class in the C++ programming language. It is part of the C++11 standard library and provides a way to manage dynamically allocated objects with automatic memory management.
Unique pointers are called "unique" because they are the only object that owns the memory they point to. This means that there can be no other unique pointers that point to the same memory. When a unique pointer goes out of scope or is deleted, it automatically deallocates the memory it owns.
The syntax for declaring a unique pointer is as follows:
```cpp
std::unique_ptr<Type> ptr(new Type);
```
This creates a unique pointer named `ptr` that points to a dynamically allocated object of type `Type`. The `new` operator is used to allocate memory for the object.
Unique pointers can also be used with arrays, in which case the syntax is:
```cpp
std::unique_ptr<Type[]> ptr(new Type[Size]);
```
This creates a unique pointer named `ptr` that points to a dynamically allocated array of `Size` objects of type `Type`.
Unique pointers can be moved, but not copied. This is because copying a unique pointer would create a second object that owns the same memory, violating the uniqueness property.
Overall, std::unique_ptr provides a safe and efficient way to manage dynamically allocated objects in C++.