Home >Backend Development >C++ >When Does `std::unique_ptr` Require a Complete Type Definition?
std::unique_ptr
In C , it's generally required that templates in the standard library be instantiated with complete types. However, std::unique_ptr and std::shared_ptr are notable exceptions. They allow for partial instantiation with incomplete types, but certain operations necessitate complete types.
This distinction arises from potential undefined behavior when deleting an object of an incomplete type. Smart pointers like std::unique_ptr and std::shared_ptr aim to prevent this by requiring complete types where necessary, ensuring that destructors are invoked correctly.
Type Completeness Requirements for std::unique_ptr
std::unique_ptr requires complete types in specific instances, as summarized below:
**Operation | Complete Type Requirement** | ||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Default constructor | Incomplete | ||||||||||||||||||||
Copy constructor | N/A (unique_ptr does not have a copy constructor) | ||||||||||||||||||||
Move constructor | Incomplete | ||||||||||||||||||||
Destructor |
|
||||||||||||||||||||
Constructor from pointer | Incomplete | ||||||||||||||||||||
Copy assignment | N/A (unique_ptr does not have a copy assignment operator) | ||||||||||||||||||||
Move assignment | Complete | ||||||||||||||||||||
reset() | Complete | ||||||||||||||||||||
reset(A*) | Complete |
The above is the detailed content of When Does `std::unique_ptr` Require a Complete Type Definition?. For more information, please follow other related articles on the PHP Chinese website!