Are there STL implementations that use operator new[]
as an allocator? I was just wondering because on my compiler, making Foo::operator new[]
private did not prevent me from creating a vector<Foo>
... is that behavior guaranteed by anything?
views:
331answers:
4C++ 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
.