std::allocator<T>::deallocate
constexpr void deallocate( T* p, std::size_t n );
void deallocate( T* p, std::size_t n );
释放指针p
所引用的存储空间,该指针必须是通过先前调用allocate() 或allocate_at_least() (C++23起)获得的。
参数n
必须等于最初生成p
的allocate()调用中的第一个参数,
或者,如果p
是从调用allocate_at_least(m)
并返回{p, count}
获得的,则n
必须在范围[m, count]内。 (自 C++23 起)
否则,行为未定义。
调用::operator delete(void*)
或::operator delete(void*, std::align_val_t)
(C++17起),但其调用时间和方式是未指定的。
在常量表达式的求值中,此函数必须释放同一表达式求值过程中分配的存储空间。 (自 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); // may throw
for (std::size_t i{}; i != n; ++i) {
// allocator.construct(&s[i], i+42); // removed in C++20
std::construct_at(&s[i], i+42); // since 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();