views:

331

answers:

4

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?

+4  A: 

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).
anon
Can't find such statement in C++ Standard. Which revision do you use?
Kirill V. Lyadvinsky
ISO/IEC 14882:1998(E)
anon
It's 20.4.1.1, not 24.4.1.1, which might explain why Kirill didn't find it.
Steve Jessop
Gah! You are right - I'll edit the answer.
anon
Wouldn't it make more sense to use `::operator new[]` instead of `::operator new` to allocate blocks of memory intended to hold a sequence of objects instead of a single object?
Fred
I'm just quoting from the standard. For discussions of WHY the standard does things, I suggest asking in the usenet group comp.std.c++
anon
+1  A: 

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.

Joe Gauterin
A vector basically allocates uninitialized memory and places objects therein later as they are added. Reserving memory does not create instances.
UncleBens
+1  A: 

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.

Jerry Coffin
A: 

If you want to prohibit the creation of your object make private constructor rather than operator new.

Alexey Malistov