Home >Backend Development >C++ >Does `std::unique_ptr` Need a Complete Definition of T?
Is std::unique_ptr
Is std::unique_ptr
Implementation-Dependent Behavior in Visual Studio 2010 SP1
The behavior in Visual Studio 2010 SP1 suggests that its implementation of std::unique_ptr requires a complete definition of Thing. This is not a standard requirement, but rather an implementation-specific choice.
Partial Exceptions in the Standard Library
While most C standard library templates require complete types, std::shared_ptr and std::unique_ptr are partial exceptions. Some of their functions can be instantiated with incomplete types, due to their role in supporting idioms like the pointer-to-implementation (pimpl) pattern. However, using incomplete types in certain operations can lead to undefined behavior, such as deleting an incomplete object.
Type Completeness Requirements for Different Operations
std::unique_ptr and std::shared_ptr require complete types in different situations. For example, ~std::unique_ptr requires a complete type for its destructor, while std::unique_ptr(A*) allows an incomplete type if the pointer is being taken over from. A table summarizes these requirements:
Operation | std::unique_ptr | std::shared_ptr |
---|---|---|
Default constructor | incomplete | incomplete |
Copy constructor | - | incomplete |
Move constructor | incomplete | incomplete |
Destructor | complete | incomplete |
Constructor from pointer | incomplete | complete |
Copy assignment | - | incomplete |
Move assignment | complete | incomplete |
Reset without argument | complete | incomplete |
Reset with argument | complete | complete |
In conclusion, while std::unique_ptr does not inherently require a complete type definition in the C standard, some implementations (like Visual Studio 2010 SP1) may impose such a requirement. It is important to be aware of the specific requirements of the implementation being used to avoid undefined behavior.
The above is the detailed content of Does `std::unique_ptr` Need a Complete Definition of T?. For more information, please follow other related articles on the PHP Chinese website!