简体   繁体   English

STL分配器和运算符new []

[英]STL allocators and operator new[]

Are there STL implementations that use operator new[] as an allocator? 是否存在使用operator new[]作为分配器的STL实现? On my compiler, making Foo::operator new[] private did not prevent me from creating a vector<Foo> ... is that behavior guaranteed by anything? 在我的编译器上,使Foo::operator new[] private并没有阻止我创建一个vector<Foo> ...这种行为是否由任何东西保证?

C++ Standard, section 20.4.1.1. C ++标准,第20.4.1.1节。 The default allocator allocate() function uses global operator new: 默认分配器allocate()函数使用全局运算符new:

pointer allocate(size_type n, allocator<void>::const_pointerhint=0);

3 Notes: Uses ::operator new(size_t) (18.4.1).

std library implementations won't use T::operator new[] for std::allocator. std库实现不会对std :: allocator使用T :: operator new []。 Most of them use their own memory pooling infrastructure behind the scenes. 他们中的大多数人在幕后使用自己的内存池基础设施。

In general, if you want to stop Foo objects being dynamically allocated, you'll have to have make all the constructors private and provide a function that creates Foo objects. 通常,如果要停止动态分配Foo对象,则必须使所有构造函数都为私有,并提供创建Foo对象的函数。 Of course, you won't be able to create them as auto variables either though. 当然,您也无法将它们创建为auto变量。

std::vector uses an Allocator that's passed as a template argument, which defaults to std::allocate. std :: vector使用一个作为模板参数传递的Allocator,默认为std :: allocate。 The allocator doesn't work like new[] though -- it just allocates raw memory, and placement new is used to actually create the objects in that memory when you tell it to add the objects (eg with push_back() or resize() ). 虽然分配器不像new[]那样工作 - 它只是分配原始内存,当你告诉它添加对象时,使用placement new来实际创建该内存中的对象(例如使用push_back()resize() )。

About the only way you could use new[] in an allocator would be if you abused things a bit, and allocated raw space using something like new char[size]; 关于在分配器中使用new[]的唯一方法是,如果你滥用了一些东西,并使用new char[size];类的东西分配原始空间new char[size]; . As abuses go, that one's fairly harmless, but it's still unrelated to your overload of new[] for the class. 随着滥用行为的发生,那个人相当无害,但它仍然与你对班级的new[]过载无关。

如果要禁止创建对象,请使用私有构造函数而不是operator new

In addition to the other answers here, if you want to prevent anyone from creating a STL container for your type Foo , then simply make the copy-constructor for Foo private (also the move-constructor if you're working with C++11). 除了这里的其他答案,如果你想阻止任何人为你的类型Foo创建一个STL容器,那么只需为Foo私有复制构造函数(如果你正在使用C ++ 11,也可以使用move-constructor) )。 All STL-container objects must have a valid copy or move constructor for the container's allocator to properly call placement new and construct a copy of the object in the allocated memory block for the container. 所有STL容器对象必须具有容器的分配器的有效副本或移动构造函数才能正确调用placement new并在容器的已分配内存块中构造对象的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM