c++ - Placement-new vs new-expression
问题描述
Again with placement new
I've found an example on this forum like this:
char *buf = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi"); // placement new
string *q = new string("hi"); // ordinary heap allocation
But I think here
buf
is a pointer to an allocated and Constructed dynamic array of default-init characters. So the characters in the array are default initialized and have an indeterminate values.I guess using the placement
new
in the second line will constructs objects on the previously constructed array of objects.Why the user didn't call
operator new
on the array allocation rather than usingnew
expression?:char *buf = static_cast<char*>(operator new[](sizeof(string)));
After all I think if
buff
is a pointer to a dynamic array of non-default-constructible objects then the code will fail to compile using the new expression rather than using the operator new function.Are my guesses correct?
Here is the link to the original answer:
解决方案
为什么用户没有在数组分配上调用 operator new 而不是使用 new 表达式?:
我们无法回答这个问题,因为我们不是那个用户。您应该向用户询问 - 尽管该示例是在 1998 年编写的,但与他们联系可能并不容易。我的猜测:他们不知道非放置运算符 new 存在,或者他们不知道它的用途。在这种情况下,重用 char 数组的内存是一种直观的选择。
请注意,首先创建单个动态std::string
对象的示例毫无意义(我假设string
示例中就是这样)。
我有一个类似的问题给你:你为什么operator new[]
在你的建议中使用而不是operator new
?更重要的是,为什么不使用分配器呢?
我的猜测正确吗?
- 正确的。
- 正确的。
- 这是一个问题,而不是猜测。我在上面介绍过。
- 它会失败。但这无关紧要,因为
char
它是默认可构造的。
推荐阅读
- python - 如何向 tf-idf 矩阵添加新功能
- c++ - 如何为 wxWidgets 编写 GUI 测试
- mongodb - mongo-cxx 驱动程序的奇点配方
- html - 有谁知道为什么 html 的 xampp 图像问题
- flutter - 使用动态数据构建页面时,setState() 不会刷新我的小部件树
- xcode - 在iOS ionic中条纹不完整的付款
- python - 尝试从 Python 执行 SQL 查询时出现 KeyError
- visual-c++ - 代码分析和 constexpr 函数 - 这个函数是一个很好的候选者吗?
- r - 为闪亮的仪表板创建登录页面
- amazon-web-services - 如何从 AWS Athena 访问成本分配标签数据