如何在我自己的容器类中使用 std::allocator
我正在尝试编写一个使用 STL 分配器的容器类。我目前所做的是拥有一个私有成员
std::allocator<T> alloc_;
(稍后将对其进行模板化,以便用户可以选择不同的分配器),然后调用
T* ptr = alloc_.allocate(1,0);
以获取指向新分配的“T”对象的指针(并使用 alloc_.construct 来调用构造函数;请参阅下面的答案)。这适用于 GNU C++ 库。
然而,对于 Solaris 上的 STLPort,这无法做正确的事情并导致各种奇怪的内存损坏错误。如果我这样做,
std::allocator_interface<std::allocator<T> > alloc_;
那么一切都会按预期进行。
使用 stl::allocator 的正确方法是什么? STLPort/Solaris版本无法用g++编译,但是g++对吗?
I am trying to write a container class which uses STL allocators. What I currently do is to have a private member
std::allocator<T> alloc_;
(this will later be templated so that the user can pick a different allocator) and then call
T* ptr = alloc_.allocate(1,0);
to get a pointer to a newly allocated 'T' object (and used alloc_.construct to call the constructor; see the answer below). This works with the GNU C++ library.
However, with STLPort on Solaris, this fails to do the right thing and leads to all sorts of bizarre memory corruption errors. If I instead do
std::allocator_interface<std::allocator<T> > alloc_;
then it is all working as it should.
What is the correct way to use the stl::allocator? The STLPort/Solaris version fails to compile with g++, but is g++ right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用分配器进行分配和构造。类似这样的:
如果你不从一个正确构造的对象开始,很多东西都会彻底损坏。想象一下一个 std::string 被分配但没有被构造。当您尝试分配给它时,它首先会尝试通过释放一些数据来清理其旧内容,这些数据当然是堆中的垃圾值并崩溃。
You need to both allocate and construct with the allocator. Something like this:
Lots of things are downright broken if you don't start with a properly constructed object. Imagine a
std::string
being allocated but not constructed. When you try to assign to it, it will first try to cleanup its old contents by freeing some data, which will of course be garbage values from the heap and crash.您可能想要做的就是拥有自己的自定义分配器,您可以使用它来查看标准容器如何与分配器交互。 Stephan T. Lavavej 发布了一个很好、简单的工具,称为
mallocator
。将其放入使用各种 STL 容器的测试程序中,您可以轻松查看标准容器如何使用分配器:并非
mallocator
中的所有接口函数(例如construct()
和destroy()
) 使用跟踪输出进行检测,因此您可能希望将跟踪语句放入其中,以便更轻松地了解标准容器如何使用这些函数,而无需借助调试器。这应该能让您很好地了解容器如何使用自定义分配器。
Something you might want to do is have your own custom
allocator
that you can use to see how the standard containers interact wit allocators. Stephan T. Lavavej posted a nice, simple one called themallocator
. Drop it into a test program that uses various STL containers and you can easily see how the allocator is used by the standard containers:Not all of the interface functions in the
mallocator
(such asconstruct()
anddestroy()
) are instrumented with trace output, so you might want to drop trace statements in there to more easily see how the standard containers might use those functions without resorting to a debugger.That should give you a good idea of how your containers might be expected to use a custom
allocator
.