c++ - 使用 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;
}
解决方案
当您调用 allocator::destroy 时,它只会破坏内存中的对象——它不会对内存做任何事情(它仍然存在)或移动任何东西。当您稍后尝试对该内存进行某些操作时,您会得到未定义的行为,但在您的字符串的情况下,“未定义的行为”结果是“就像它是一个空字符串一样”,因此没有任何内容被打印。
如果您要a1.construct(wrd+1, "three");
在调用 ins 您的字符串代码之后调用a1.destroy
(使其与您的 int 代码相同),您会看到它打印one three three
推荐阅读
- optimization - 运行贝叶斯优化器,当执行最大化函数时,“下限之一大于上限”。发生错误
- vuetify.js - 列表项内的 Vuetify 菜单 - 可点击区域并非一直到边缘
- android - Android 中忽略开发者设置动画比例
- javascript - 如何知道发送了多少中止的 POST 请求?
- reactjs - raspbian、react 和 lxsession 自动启动 - 节点未启动
- c++ - C++ 内置的固定宽度类型,没有额外的包含
- html - 带背景的 CSS 箭头
- tensorflow - “LookupError:梯度注册表没有条目:shap_TensorListStack”使用 DeepExplainer for Keras 模型
- java - 尝试制作一个自动自定义对话框
- wpf - MVVM 灯。当属性的值真正改变时执行方法的正确方法