物体的真正破坏是什么?如果你这样做:
class K {
public:
K (int m) {v = m;}
int v;
};
Class * x = reinterpret_cast <K*> (:: operator new (sizeof (K)));
new ((void *) x) K (2);
x-> ~ C ();
cout << x-> v; / / result: 2
:: operator delete ((void *) v);Deconstructor什么也没做!(?)为什么?
发布于 2014-03-16 21:10:05
有两套你正在处理的想法:
重要的是要了解如何正确地将它们结合起来。
假设你有一个功能:
void f1()
{
// Construct an object.
// The constructor gets called.
K k(10);
// Do something with the object.
// Done with the function
// The object k gets destructed.
// The destructor gets called.
}在此函数中,您将在堆栈上构造对象。从函数返回时,析构函数将自动调用。将自动为您从堆栈中分配和卸载内存。
现在,让我们看另一个函数。
void f2()
{
// Allocate memory for the object.
// Use that Construct an object .
// The constructor gets called.
K* k = new K(10);
// Do something with the object.
// Done with the function
// Delete the object.
// The destructor gets called.
// Deallocate the memory.
delete k;
}这个函数中的这一行K* k = new K(10);执行两个操作--它从堆中为对象分配内存,并调用构造函数来构造对象。
行delete k;还合并了两个操作。它首先调用析构函数,然后从堆中释放内存。如果您没有delete k;,该函数将泄漏new K(10)分配的内存。
这里,我们使用了new和delete运算符。
现在来看一下如何使用全局operator new和operator delete函数。
void f3()
{
// Allocate memory for the object from the heap.
void* p = ::operator new(sizeof(K));
// At this point, an object of type K has not been constructed yet.
K* k1 = reinterpret_cast<K*>(p);
// Using the reinterpret_cast to treat the `void*` as a `K*` does not
// change that fact. An object of type K has not yet been constructed still.
K* k2 = new (p) K(10);
// Use placement new operator to construct K.
// At this point, an object of type K has been constructed by calling
// K's constructor using the memory pointed to by p.
// Do something with the object.
// Done with the function.
// Now it's time to do the necessary things to release resources back to
// the system.
// Do not use `delete K` at this point.
// Whenever you use the placement new operator, call the destructor explicitly.
// This calls the destructor ~K(), but does not deallocate memory from heap.
k2->~K();
// Deallocate the memory heap.
::operator delete(p);
}发布于 2014-03-16 20:39:36
你以为它会做什么(排字除外)?你有一个POD类型,不需要任何破坏发生。尝试同样的东西,比如,在里面放一个std::string,那么析构函数实际上会做一些事情。
然后,把这些实验放在一边,如果在接下来的20年中,您确实需要放置新的和显式调用的析构函数,那么将一些调试输出放在需要的析构函数中,并检查它是否实际被调用。
发布于 2014-03-16 22:38:15
Deconstructor什么也没做!(?)为什么?
因为在这种情况下它是空的。你以为它会做什么呢?
https://stackoverflow.com/questions/22442548
复制相似问题