c++新内存替换和作用域解析
C++ new - memory substitution and scope resolution
我在看下面的代码:
// operator new example
#include <iostream> // std::cout
#include <new> // ::operator new
struct MyClass {
int data[100];
int kk;
MyClass(int ea) : kk(ea) {std::cout << "constructed [" << this << "]n";}
};
int main () {
std::cout << "1: ";
MyClass * p1 = new MyClass(1);
// allocates memory by calling: operator new (sizeof(MyClass))
// and then constructs an object at the newly allocated space
std::cout << "2: ";
MyClass * p2 = new (std::nothrow) MyClass(2);
// allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
// and then constructs an object at the newly allocated space
std::cout << "3: ";
new (p2) MyClass(3);
// does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
// but constructs an object at p2
// Notice though that calling this function directly does not construct an object:
std::cout << "4: ";
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
// allocates memory by calling: operator new (sizeof(MyClass))
// but does not call MyClass's constructor
delete p1;
delete p2;
delete p3;
return 0;
}
我有两个问题:
对象2是否在执行
时被销毁new (p2) MyClass(3);
应该在对象2的分配空间中构造对象3 ?
- 行
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
在没有::的情况下也可以工作,那么在没有类/命名空间的情况下使用作用域解析操作符的目的是什么?
首先,没有调用第二个对象的析构函数。在原来的位置初始化一个新对象。如果愿意,可以在重用对象的内存之前,用p2->~MyClass();
显式地调用对象的析构函数。
其次,使用::
限定分配函数的目的是确保它来自全局名称空间。标准隐式地为所有翻译单元定义了operator new
的两个重载,如果包含<new
>,则会得到一些额外的重载。所有这些都是在全局命名空间中定义的(而不是在std
中)。可以为类重载operator new
(只需将它们作为成员函数提供),因此使用::
进行限定可以确保使用全局版本。
Answer1:当您为新对象重用它的内存时,位于p2
的对象的生命周期结束。它不会运行析构函数,所以它不会被干净地"销毁",尽管只有POD成员而没有用户声明的析构函数,但在这种情况下,这没有什么区别。
Answer2:使用::
强制查找operator new
只考虑在全局作用域声明的operator new
。在您调用operator new
的作用域中,在任何情况下都不会考虑其他operator new
,因此没有区别。
相关文章:
- C++具有不同作用域的相同名称的名称解析规则
- 用于返回嵌套类类型的作用域解析运算符
- 变量声明中结构的作用域解析是什么意思
- 模板类中静态函数或指针的作用域解析
- 作用域解析运算符和常量
- 模板子类作用域解析
- ::(作用域解析运算符)在C++中用于多种用途
- 使用指向成员的指针时,如何通过作用域解析运算符获取类成员的地址
- 带有继承的C++作用域解析用法
- ::c++中模板函数调用前面的作用域解析运算符
- 用预处理器#define替换作用域标识符
- 为什么作用域解析对覆盖的变量不起作用?
- isalnum的作用域解析运算符
- c++新内存替换和作用域解析
- 为什么c++的作用域解析操作符是::
- ::操作符能否出现在与限定名查找中的作用域解析不同的上下文中?
- c++语言中的块作用域解析
- 在类定义的类名中,作用域解析操作符的作用是什么?
- 关于c++中作用域解析操作符的问题
- 为什么基类构造函数没有被作用域解析操作符调用