为什么 ::运算符关键字添加到 new 之前用于内存分配
why ::operator keyword added before new for memory allocation?
在理解事物时,我遇到了以下代码行。
int *p2 = (int *) ::operator new (sizeof(int));
*p2 = 100;
delete p2;
我理解逻辑和任务,但为什么要在 new 之前添加这个"::运算符"关键字?
我应该如何进一步阅读?
我知道以下几行:
p2 = new int;
*p2 = 100;
delete p2;
operator new
是一个基本的内存分配函数。 new
为对象分配内存并对其进行初始化。
对于像int
这样的内置类型没有太大区别,但对于像std:string
这样的非POD(*)类型来说,这种差异至关重要。
int *p2 = (int*) :: operator new(sizeof(int));
int i = *p2; // ERROR. *p2 is not (yet) an int - just raw, uninitialized memory.
*p2 = 100; // Now the memory has been set.
std::string *s2 = (std::string*) :: operator new(sizeof(std::string));
std::string str = *s2; // ERROR: *s2 is just raw uninitialized memory.
*s2 = "Bad boy"; // ERROR: You can only assign to a properly
// constructed string object.
new(s2) std::string("Constructed"); // Construct an object in the memory
// (using placement new).
str = *s2; // Fine.
*s2 = "Hello world"; // Also fine.
*:POD 代表"普通旧数据"。
相关文章:
- 开放 CV 中的动态内存分配,用于视频处理
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 基于浅树的数据结构的内存分配器,用于频繁分配和解除分配
- make_pair和大括号 { } 之间的区别,用于在C++中分配一对?
- C++将shared_ptr用于连续分配的内存
- 本地分配的内存是否可以用于将来使用?
- 在 C++ 中,用于将大型 2D 数组转换为 1D 数组的内存分配
- 用于删除复制/移动分配运算符的有效签名
- 用于批处理分配的库
- COPY分配被禁用于C 11中的线程
- 用于创建 HDF5 数据集的 4 维 c++ 数组的动态内存分配
- 好的设计?用于分配的智能指针与用于访问的原始指针相结合
- C++ - 重载'=',用于将十六进制值分配给对象
- 此TreeVisitor函数如何用于此二进制搜索树分配
- (C++)用于实例化新对象并将其分配给指向相同对象类型的指针的 2D 向量的语法
- 分配参数用于测试目的
- 为什么 ::运算符关键字添加到 new 之前用于内存分配
- 用于堆分配的对象的设置器
- 用于分配和检索的括号过载;const,引用
- 内存管理——用于分配/释放I/O缓冲区的现代c++风格