【发布时间】:2016-09-05 21:44:20
【问题描述】:
这个问题来自我之前的问题:Why shouldn't C++ operator new/delete/variants be in header files?。快速总结一下,我正在学习覆盖全局运算符 new、delete 等。我现在需要一个自定义分配器类(我的重载运算符 new 调用 std::set::insert(...),它本身似乎调用 new,因此无限回避)。我认为如果我向我的std::set 提供一个自定义分配器(例如,使用malloc 而不是new),我可以绕过无限递归。
我已经阅读了一些关于实现自定义分配器的文章,但对 struct rebind 的语义有些困惑。
这里有一个很好的问答:Parsing allocator::rebind calls,但我仍然对一个特定的项目感到困惑。 cplusplus.com 说struct rebind:
它的成员类型other是分配Type类型元素的等价分配器类型
我不明白other 是如何成为struct rebind 的成员的。我发现struct rebind 的定义如下:
template <class Type> struct rebind {
typedef allocator<Type> other;
};
我看不出other 是struct rebind 的成员变量。这只是typedefed。如果我在全局命名空间中做了typedef int foo;,那并不意味着在全局命名空间中声明了int类型的全局变量,那么反过来,other如何成为struct rebind的成员?
顺便说一句,我知道(或者至少我已经读过)在 C++11 之后这一切都得到了简化,但我仍然想先了解这一点,这样我才能掌握基础知识。感谢您的帮助。
在这个话题上,有人能解释一下在结构中处理typedefing 吗?我以前在回答者 Johannes Schaub 的 amazing example 中看到过一次,但我还没有完全理解它。在我看来,它似乎将 typedef 的范围限制在包含结构的实例内。
更新:
我想将此添加到我的问题中。使用来自 cppreference.com 的这个精简示例:
#include <memory>
#include <iostream>
#include <string>
int main()
{
std::allocator<int> a1; // default allocator for ints
decltype(a1)::rebind<std::string>::other a2_1;
}
decltype(a1)::rebind<std::string>::other a2_1; 的行不是说std::allocator<std::string> a2_1; 很长吗?
【问题讨论】:
-
typedefing 在struct中允许您根据给定模板选择类型。就这样。你可能有专门的专业来做一些特别的事情,但就是这样。虽然,make_integer_sequence的实现使用了一些很酷的递归来满足您的需求。
标签: c++ memory memory-management