STL 分配器和运算符 new[]
是否有使用operator new[]
作为分配器的STL实现?在我的编译器上,将 Foo::operator new[]
设为私有并不会阻止我创建 vector
...这种行为有什么保证吗?
Are there STL implementations that use operator new[]
as an allocator? On my compiler, making Foo::operator new[]
private did not prevent me from creating a vector<Foo>
... is that behavior guaranteed by anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++ 标准,第 20.4.1.1 节。默认分配器 allocate() 函数使用全局运算符 new:
C++ Standard, section 20.4.1.1. The default allocator allocate() function uses global operator new:
std 库实现不会使用 T::operator new[] 作为 std::allocator。他们中的大多数在幕后使用自己的内存池基础设施。
一般来说,如果您想停止动态分配
Foo
对象,则必须将所有构造函数设为私有,并提供创建Foo
对象的函数。当然,您也无法将它们创建为auto
变量。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 createsFoo
objects. Of course, you won't be able to create them asauto
variables either though.std::vector 使用作为模板参数传递的分配器,默认为 std::allocate。不过,分配器的工作方式与 new[] 不同——它只是分配原始内存,当您告诉它时,放置 new 用于在该内存中实际创建对象添加对象(例如使用
push_back()
或resize()
)。在分配器中使用 new[] 的唯一方法是滥用一些东西,并使用 new char[size]; 之类的东西分配原始空间。就滥用而言,这种行为相当无害,但它仍然与类的
new[]
重载无关。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 placementnew
is used to actually create the objects in that memory when you tell it to add the objects (e.g. withpush_back()
orresize()
).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 likenew char[size];
. As abuses go, that one's fairly harmless, but it's still unrelated to your overload ofnew[]
for the class.如果您想禁止创建对象,请使用私有构造函数而不是
operator new
。If you want to prohibit the creation of your object make private constructor rather than
operator new
.除了这里的其他答案之外,如果您想阻止任何人为您的类型
Foo
创建 STL 容器,那么只需将Foo
的复制构造函数设为私有(也可以如果您使用的是 C++11,则为移动构造函数)。所有 STL 容器对象都必须具有有效的复制或移动构造函数,以便容器的分配器正确调用放置 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 forFoo
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 placementnew
and construct a copy of the object in the allocated memory block for the container.