C ++在销毁分配器中的元素时会导致双重释放 ?

问题描述 投票:0回答:1

C ++分配器。我知道String会在内部实现中使用new分配一个块缓冲区,并在Destructor中释放它(调用delete [])。

我的问题是,使用allocator<string>时是否会免费提供双倍?

  1. 首先在字符串析构函数处释放。
  2. 第二个到字符串的释放缓冲区点已释放。

另外,字符串和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;
}
c++ std allocator
1个回答
0
投票

[当您写这样的东西时:

Foo *foo = new Foo();

发生两件事:

  1. Foo对象分配了一些堆空间。
  2. Foo()构造函数被调用,this指向新分配的空间。

稍后,您删除Foo对象:

delete foo;

还有另外两件事发生:

  1. 析构函数~Foo()被调用。
  2. 为Foo实例分配的内存被释放回堆。

std::allocator类仅允许您手动执行这四个步骤。

如果您有一个allocator<string> alloc,然后依次调用alloc.allocatealloc.construct,则与执行new string()相同。当您依次调用alloc.destroyalloc.deallocate时,这与删除string指针相同。

因此,不会有任何额外的免费活动。对destroy的调用会导致string释放为其缓冲区分配的任何内存,然后对deallocate的调用将释放用于string对象本身的内存。

© www.soinside.com 2019 - 2024. All rights reserved.