std::default_delete
STD::默认[医]删除
Defined in header | | |
---|---|---|
template< class T > struct default_delete | (1) | (since C++11) |
template< class T > struct default_delete<T[]> | (2) | (since C++11) |
std::default_delete
使用的默认销毁策略。std::unique_ptr
当未指定删除项时。
1%29非专业default_delete
使用delete
若要释放单个对象的内存,请执行以下操作。
2%29数组类型的部分专门化,它使用delete[]
也提供了。
成员函数
(constructor) | constructs a default_delete object (public member function) |
---|---|
operator() | deletes the object or array (public member function) |
STD::默认[医]删除::默认[医]删除
constexpr default_delete() = default; | (1) | |
---|---|---|
template <class U> default_delete( const default_delete<U>& d | (2) | (member only of generic default_delete template) |
template<class U> default_delete( const default_delete<U[]>& d | (3) | (since C++17)(member only of the array default_delete specialization) |
1%29构造一个std::default_delete
对象。
2%29构造一个std::default_delete
对象来自另一个std::default_delete
对象。此构造函数将只参与重载解决方案。U*
隐式可转换为T*
...
3%29构造一个std::default_delete<U[]>对象来自另一个std::default_delete<U[]>对象。此构造函数将只参与重载解决方案。U(*)[]隐式可转换为T(*)[]...
参数
d | - | a deleter to copy from |
---|
例外
noexcept
规格:
noexcept
注记
大转换构造函数模板std::default_delete的隐式转换成为可能。std::unique_ptr<Derived>到std::unique_ptr<Base>...
STD::默认[医]删除::操作员%28%29
void operator()(T* ptr) const; | (1) | (as of C++17, no longer a member of the default_delete |
---|---|---|
template <class U> void operator()(U* ptr) const; | (2) | (member only of default_delete<T[]> template specialization, but defined as deleted prior to C++17) |
1) Calls delete (primary template) or delete on ptr 2) Defined as deleted | (until C++17) |
---|---|
1) Calls delete on ptr 2) Calls delete[] on ptr. This function will only participate in overload resolution if U(*)[] is implicitly convertible to T(*)[]. | (since C++17) |
在任何情况下,如果U是一个不完整的类型,程序是错误的。
参数
ptr | - | an object or array to delete |
---|
例外
没有例外的保证。
调用不完全类型
在代码中调用运算符%28%29时,类型必须完成。在某些实现中,static_assert
是用来确保是这样的。这个要求的原因是调用删除在不完全类型上,如果完整类类型具有非平凡析构函数或解分配函数,则在C++中是未定义的行为,因为编译器无法知道这些函数是否存在并必须调用。
例
二次
#include <memory>
#include <vector>
#include <algorithm>
int main()
{
// {
// std::shared_ptr<int> shared_bad(new int[10]
// } // the destructor calls delete, undefined behavior
{
std::shared_ptr<int> shared_good(new int[10], std::default_delete<int[]>
()
} // the destructor calls delete[], ok
{
std::unique_ptr<int> ptr(new int(5)
} // unique_ptr<int> uses default_delete<int>
{
std::unique_ptr<int[]> ptr(new int[10]
} // unique_ptr<int[]> uses default_delete<int[]>
// default_delete can be used anywhere a delete functor is needed
std::vector<int*> v;
for(int n = 0; n < 100; ++n)
v.push_back(new int(n)
std::for_each(v.begin(), v.end(), std::default_delete<int>()
}
二次
另见
unique_ptr (C++11) | smart pointer with unique object ownership semantics (class template) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。