【发布时间】:2014-10-30 00:26:01
【问题描述】:
内存复用是什么意思?例如,我们创建了对象。
struct A { };
A *a = new A;
void *p = operator new(sizeof(A),a); //Is it memory reusing?
void *p = realloc(sizeof(A),a); //Is it memory reusing?
我问这个问题是因为第 3.8/6 节中的示例让我感到困惑。例子:
#include <cstdlib>
struct B {
virtual void f();
void mutate();
virtual ~B();
};
struct D1 : B { void f(); };
struct D2 : B { void f(); };
void B::mutate() {
new (this) D2; //1, reuses storage — ends the lifetime of *this
f(); // undefined behavior
... = this; // OK, this points to valid memory
}
也就是说,在//1,我们首先调用placement-new,它重用了内存,然后我们构造了一个新对象。对吧?
【问题讨论】:
-
为什么是未定义的行为?
-
@david.pfx:见stackoverflow.com/questions/9117358/…
-
分配函数的放置形式是always一个no-op。 (库版本是,如果您替换库版本,标准会使您的整个程序行为未定义,请参阅
[new.delete.placement]部分) -
@BenVoigt:不,我不这么认为。我想一定是S3.8/5
the pointer is used to access a non-static data member or call a non-static member function of the object。 -
@david.pfx:我上面的两个cmets完全没有关系。
标签: c++ struct new-operator