首页 > 解决方案 > 使用 std::allocator C++ 时字符串和 int 之间的区别

问题描述

我正在尝试了解 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++memoryallocation

解决方案


当您调用 allocator::destroy 时,它只会破坏内存中的对象——它不会对内存做任何事情(它仍然存在)或移动任何东西。当您稍后尝试对该内存进行某些操作时,您会得到未定义的行为,但在您的字符串的情况下,“未定义的行为”结果是“就像它是一个空字符串一样”,因此没有任何内容被打印。

如果您要a1.construct(wrd+1, "three");在调用 ins 您的字符串代码之后调用a1.destroy(使其与您的 int 代码相同),您会看到它打印one three three


推荐阅读