【发布时间】:2021-06-08 01:56:04
【问题描述】:
我在 Microsoft 文档网站上阅读了有关 typedefs 与 using 的信息:Aliases and typedefs (C++)
#include <stdlib.h>
#include <new>
template <typename T> struct MyAlloc {
typedef T value_type; // Failed to understand why it is needed
MyAlloc() { }
template <typename U> MyAlloc(const MyAlloc<U>&) { } // Failed to understand why it is needed
bool operator==(const MyAlloc&) const { return true; } // Failed to understand why always true
bool operator!=(const MyAlloc&) const { return false; } // Failed to understand why always false
T * allocate(const size_t n) const {
if (n == 0) {
return nullptr;
}
if (n > static_cast<size_t>(-1) / sizeof(T)) // Failed to understand this operation
{
throw std::bad_array_new_length();
}
void * const pv = malloc(n * sizeof(T));
if (!pv) {
throw std::bad_alloc();
}
return static_cast<T *>(pv);
}
void deallocate(T * const p, size_t) const {
free(p);
}
};
#include <vector>
using MyIntVector = std::vector<int, MyAlloc<int>>;
#include <iostream>
int main ()
{
MyIntVector foov = { 1701, 1764, 1664 };
for (auto a: foov) std::cout << a << " ";
std::cout << "\n";
return 0;
}
正如我在整个代码中评论的那样,我在很多地方都无法理解这段代码。有人可以为 C++ 初级到中级水平的人解释上述代码吗?
【问题讨论】:
-
StackOverflow 不是一个教程网站。您对代码到底有什么不明白的地方?请提出具体问题。
-
您的班级必须满足某些标准才能成为合适的分配器。请参阅 cppreference 上的 Allocator 要求,了解您的分配器必须提供的确切内容。
-
请在每个帖子中提出一个具体问题,我在这篇帖子中看到至少 4 个单独的问题。