Namespaces
Variants

std::allocator<T>:: deallocate

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
void deallocate ( T * p, std:: size_t n ) ;
(自 C++20 起为 constexpr)

释放指针 p 所引用的存储空间,该指针必须是通过先前调用 allocate() allocate_at_least() (since C++23) 获得的指针。

参数 n 必须等于最初生成 p 时调用 allocate() 的第一个参数, 或者当 p 是通过调用 allocate_at_least ( m ) 获得 { p, count } 返回值时,需在范围 [ m , count ] (C++23 起) ;否则行为未定义。

调用 :: operator delete ( void * ) :: operator delete ( void * , std:: align_val_t ) (C++17 起) ,但未规定其调用时机与方式。

在常量表达式求值过程中,此函数必须释放同一表达式求值期间分配的存储空间。

(since C++20)

目录

参数

p - allocate() allocate_at_least() (C++23 起) 获取的指针
n - 先前传递给 allocate() 的对象数量,或通过 allocate_at_least() 请求与实际分配数量之间的值(可能等于任一界限) (C++23 起)

返回值

(无)

示例

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <memory>
#include <string>
class S
{
    inline static int n{1};
    int m{};
    void pre() const { std::cout << "#" << m << std::string(m, ' '); }
public:
    S(int x) : m{n++} { pre(); std::cout << "S::S(" << x << ");\n"; }
    ~S() { pre(); std::cout << "S::~S();\n"; }
    void id() const { pre(); std::cout << "S::id();\n"; }
};
int main()
{
    constexpr std::size_t n{4};
    std::allocator<S> allocator;
    try
    {
        S* s = allocator.allocate(n); // 可能抛出异常
        for (std::size_t i{}; i != n; ++i)
        {
        //  allocator.construct(&s[i], i + 42); // C++20 中已移除
            std::construct_at(&s[i], i + 42);   // C++20 起
        }
        std::for_each_n(s, n, [](const auto& e) { e.id(); });
        std::destroy_n(s, n);
        allocator.deallocate(s, n);
    }
    catch (std::bad_array_new_length const& ex) { std::cout << ex.what() << '\n'; }
    catch (std::bad_alloc const& ex) { std::cout << ex.what() << '\n'; }
}

输出:

#1 S::S(42);
#2  S::S(43);
#3   S::S(44);
#4    S::S(45);
#1 S::id();
#2  S::id();
#3   S::id();
#4    S::id();
#1 S::~S();
#2  S::~S();
#3   S::~S();
#4    S::~S();

另请参阅

分配未初始化的存储空间
(公开成员函数)
分配至少达到请求大小的未初始化存储空间
(公开成员函数)
[static]
使用分配器解分配存储空间
( std::allocator_traits<Alloc> 的公开静态成员函数)