为什么:: operator关键字在新内存分配之前添加?

时间:2017-01-05 10:43:17

标签: c++ memory dynamic-memory-allocation

在了解事情的同时,我遇到了以下代码行。

int *p2 = (int *) ::operator new (sizeof(int)); 
*p2 = 100;
delete p2;

我理解逻辑和任务,但为什么在新的之前添加“:: operator”关键字?

我应该如何进一步阅读?

我知道以下几行:

p2 = new int;
*p2 = 100;
delete p2;

1 个答案:

答案 0 :(得分:3)

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