c++ - struct rebind::other 是什么意思?

标签 c++ memory memory-management

这个问题源于我的上一个问题:Why shouldn't C++ operator new/delete/variants be in header files? 。快速总结一下,我正在学习覆盖全局运算符 new , delete我现在需要一个自定义分配器类(我的重载运算符 new 调用 std::set::insert(...) ,它本身似乎调用 new ,因此无限递归)。我认为如果我向我的 malloc 提供自定义分配器(例如,使用 new 而不是 std::set )我可以绕过无限递归。

我已经阅读了一些有关实现自定义分配器的内容,并且对 struct rebind 的语义有点困惑.

这里有一个很好的问答:Parsing allocator::rebind calls ,但我仍然对某一特定项目感到困惑。 cplusplus.com 说 struct rebind :

Its member type other is the equivalent allocator type to allocate elements of type Type

我不明白怎么办otherstruct rebind 的成员。 struct rebind 的定义我发现看起来像:

template <class Type> struct rebind {
  typedef allocator<Type> other;
};

我不明白怎么办otherstruct rebind 的成员变量。只是typedef编辑。如果我这样做typedef int foo;在全局命名空间中,这并不意味着存在 int 类型的全局变量在全局命名空间中声明,那么 other 又是如何声明的?成为 struct rebind 的成员(member)?

顺便说一句,我知道(或者至少我读过)这一切在 C++11 后都得到了简化,但我仍然想先了解这一点,以便我掌握基础知识。感谢您的帮助。

在这个主题上,有人可以解释一下 typedef 的处理吗?在结构内?我以前在这个amazing example见过一次来自回答者约翰内斯·绍布(Johannes Schaub),但我还没有完全理解它。对我来说,它看起来像是将 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;

最佳答案

I don't see how other is a member variable of struct rebind.

事实并非如此。

It's just typedefed.

没错。正如引用所述,它是一个成员类型

While on this topic, can someone also explain the deal with typedefing within a struct? I've seen it once before in this amazing example from answerer Johannes Schaub, but I don't fully grok it yet.

很难给出一个不存在相同问题的示例(因为您没有说明您对 litb 示例的不理解之处),但我们开始:

struct Foo
{
   typedef int bar;
};

Foo::bar x = 42;  // creates an int named `x`, because Foo::bar is int

To me it looks like it's restricting the scope of the typedef to within an instance of the containing struct.

没错。生成的类型是该类的成员,就像嵌套类一样,并且就像类是其封闭命名空间的成员一样。

By the way, I know (or at least I've read that) this has all been simplified post C++11

不,成员类型在该语言的任何修订版中都没有从根本上改变(尽管新的 using 语法可选地使声明它们变得更容易)。

If I did typedef int foo; in the global namespace, that doesn't mean there's a global variable of type int declared in the global namespace

不,但是会有一个名为 foo类型在全局命名空间中。

Isn't the line decltype(a1)::rebind<std::string>::other a2_1; a long way of saying std::allocator<std::string> a2_1; ?

是的;一条漫长的路,一条无论如何都行得通的路a1是(所以结果可能根本不是std::allocator<T>)。当您编写模板时,这一点很重要。

关于c++ - struct rebind::other 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338032/

相关文章:

C++ 错误 : expected '=' , ','、 ';'、 'asm' 或 '__attribute__'(类名)之前的 'I2Cdev'

c# - 如何诊断 "The instruction at 0x......... referenced memory at 0x00000000"

c++ - 指针还是数组?

c# - IEnumerable 如何存储在 c# 中的内存中?

c++ - 将 vector 或参数传递给 boost::process (boost::fusion)

c++ - 使用 dll 中的类函数

PHP 内存限制

memory-management - 沙盒与虚拟化

c++ - 嵌套模板类特化的语法

linux - linux如何保存系统状态信息?