STL allocators and operator new[]
Are there STL implementations that use operator new[]
as an allocator? On my compiler, making Foo:开发者_JS百科:operator new[]
private did not prevent me from creating a vector<Foo>
... is that behavior guaranteed by anything?
C++ Standard, section 20.4.1.1. The default allocator allocate() function uses global operator 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. 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. Of course, you won't be able to create them as auto
variables either though.
std::vector uses an Allocator that's passed as a template argument, which defaults to 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 (e.g. with push_back()
or 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];
. As abuses go, that one's fairly harmless, but it's still unrelated to your overload of new[]
for the class.
If you want to prohibit the creation of your object make private constructor rather than 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). 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.
精彩评论