C++ C++;新-内存替换和作用域解析
我正在查看以下代码:C++ C++;新-内存替换和作用域解析,c++,memory,new-operator,C++,Memory,New Operator,我正在查看以下代码: // 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 &l
// 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的分配空间中构造对象3吗
- 线路
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
如果前面没有类/命名空间,那么使用作用域解析运算符的目的是什么?首先,不,不调用第二个对象的析构函数。一个新对象刚刚初始化到位。如果愿意,可以使用
p2->~MyClass()显式调用对象的析构函数代码>然后再重新使用其内存
其次,使用:
限定分配函数的目的是确保它来自全局名称空间。该标准为所有翻译单元隐式定义了两个重载运算符new
,如果包含,则会得到一些额外的内容。所有这些都是在全局命名空间中定义的(而不是在std
中)。可以为类重载操作符new
(只需将它们作为成员函数提供),因此使用:
进行限定可以确保使用全局版本。回答1:p2
中的对象的生命周期在您将其内存重新用于新对象时结束。它不会运行它的析构函数,所以它不会被干净地“销毁”,尽管只有POD成员,没有用户声明的析构函数,在这种情况下,它没有任何区别
回答2:使用<代码>::/>代码强制查找<代码>运算符new <代码>,只考虑在全局范围内声明的<代码>运算符new <代码>。在您调用的范围内,没有其他任何情况下会考虑的新操作员,因此这没有任何区别。
两个问题应该意味着两个问题。我手头没有标准副本,但我敢打赌你第一个问题的答案是否定的。你的第二个问题在这里得到了回答:
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));