为什么 ::运算符关键字添加到 new 之前用于内存分配

why ::operator keyword added before new for memory allocation?

本文关键字:用于 分配 内存 运算符 关键字 添加 为什么 new      更新时间:2023-10-16

在理解事物时,我遇到了以下代码行。

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 代表"普通旧数据"。