使用std :: allocator C ++时字符串和整数之间的差异

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

我正在尝试了解std :: allocator的工作方式,并尝试完成一个简单的任务。任务是删除例如第二个元素,并在删除元素后将其向左移动。

例如,我们将其作为输入数组:1,2,3,其输出应类似于1,3。我得到的输入是:1,3,3

这件事没有发生,这就是为什么我在这里问你。

但是,当我使用**std::allocator<string> myVar**而不是**std::allocator<int> myVar**时,它可以工作。

然后输入:一个,两个,三个,输出为:一个,三个

这里是使用std::allocator<int>的代码:

 #include <iostream>
 #include <memory>

using namespace std;

int main()
{
    allocator<int> a1;

    int* arr = a1.allocate(3);

    for (int i = 0; i < 3; i++)
        a1.construct(arr + i, i + 1);

    a1.destroy(arr + 1);
    a1.construct(arr + 1, 3);

    for (int i = 0; i < 3; i++)
        cout << arr[i] << " ";
    cout << endl;

    a1.deallocate(arr, 3);
    return 0;
}

这是std::allocator<string>的代码:

#include <iostream>
#include <memory>
#include <string>

using namespace std;

int main()
{
    allocator<string> a1;

    string* wrd = a1.allocate(3);

    a1.construct(wrd, "one");
    a1.construct(wrd + 1, "two");
    a1.construct(wrd + 2, "three");

    a1.destroy(wrd + 1);

    cout << wrd[0] << " " << wrd[1] << " " << wrd[2] << endl;

    a1.deallocate(wrd, 3);

    return 0;
}
c++ memory allocation
1个回答
0
投票
当您调用allocator :: destroy时,它只是破坏了内存中的对象-它对内存没有任何作用(它仍然存在)或移动任何东西。稍后当您尝试使用该内存进行处理时,会得到未定义的行为,但是对于字符串,“未定义的行为”原来是“像是一个空字符串一样起作用”,因此不会打印任何内容。] >
© www.soinside.com 2019 - 2024. All rights reserved.