C ++分配器。我知道String会在内部实现中使用new
分配一个块缓冲区,并在Destructor中释放它(调用delete [])。
我的问题是,使用allocator<string>
时是否会免费提供双倍?
另外,字符串和allocate(n)
的缓冲区地址是否具有相同的区域?
#include <iostream>
#include <memory>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
const int cnt = 10;
allocator<string> alloc;
auto p = alloc.allocate(cnt);
alloc.construct(p);
for (int i = 0; i < cnt; ++i)
{
cout << p+i << endl; // print buffer address
}
alloc.destroy(p); // will it free buffer of string?
alloc.deallocate(p, cnt); // will it free buffer of string again?
return 0;
}
[当您写这样的东西时:
Foo *foo = new Foo();
发生两件事:
Foo
对象分配了一些堆空间。Foo()
构造函数被调用,this
指向新分配的空间。稍后,您删除Foo
对象:
delete foo;
还有另外两件事发生:
~Foo()
被调用。std::allocator
类仅允许您手动执行这四个步骤。
如果您有一个allocator<string> alloc
,然后依次调用alloc.allocate
和alloc.construct
,则与执行new string()
相同。当您依次调用alloc.destroy
和alloc.deallocate
时,这与删除string
指针相同。
因此,不会有任何额外的免费活动。对destroy
的调用会导致string
释放为其缓冲区分配的任何内存,然后对deallocate
的调用将释放用于string
对象本身的内存。