为什么::operator 关键字添加在new 之前用于内存分配?
why ::operator keyword added before new for memory allocation?
在理解事物的过程中,我遇到了以下代码行。
int *p2 = (int *) ::operator new (sizeof(int));
*p2 = 100;
delete p2;
我理解逻辑和任务,但是为什么在new之前添加这个"::operator"关键字?
关于这个我应该如何进一步阅读?
我知道以下几行:
p2 = new int;
*p2 = 100;
delete p2;
operator new
is a basic memory allocation function. new
为一个对象分配内存并初始化它.
对于像 int
这样的内置类型没有太大区别,但是对于像 std:string
.[=17= 这样的非 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代表"plain old data".
在理解事物的过程中,我遇到了以下代码行。
int *p2 = (int *) ::operator new (sizeof(int));
*p2 = 100;
delete p2;
我理解逻辑和任务,但是为什么在new之前添加这个"::operator"关键字?
关于这个我应该如何进一步阅读?
我知道以下几行:
p2 = new int;
*p2 = 100;
delete p2;
operator new
is a basic memory allocation function. new
为一个对象分配内存并初始化它.
对于像 int
这样的内置类型没有太大区别,但是对于像 std:string
.[=17= 这样的非 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代表"plain old data".