首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >deconstructor很懒,为什么?

deconstructor很懒,为什么?
EN

Stack Overflow用户
提问于 2014-03-16 20:30:13
回答 3查看 111关注 0票数 1

物体的真正破坏是什么?如果你这样做:

代码语言:javascript
复制
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什么也没做!(?)为什么?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-16 21:10:05

有两套你正在处理的想法:

  1. 建造和销毁物体
  2. 内存的分配和取消分配。

重要的是要了解如何正确地将它们结合起来。

假设你有一个功能:

代码语言:javascript
复制
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.
}

在此函数中,您将在堆栈上构造对象。从函数返回时,析构函数将自动调用。将自动为您从堆栈中分配和卸载内存。

现在,让我们看另一个函数。

代码语言:javascript
复制
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)分配的内存。

这里,我们使用了newdelete运算符。

现在来看一下如何使用全局operator newoperator delete函数。

代码语言:javascript
复制
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);
}
票数 3
EN

Stack Overflow用户

发布于 2014-03-16 20:39:36

你以为它会做什么(排字除外)?你有一个POD类型,不需要任何破坏发生。尝试同样的东西,比如,在里面放一个std::string,那么析构函数实际上会做一些事情。

然后,把这些实验放在一边,如果在接下来的20年中,您确实需要放置新的和显式调用的析构函数,那么将一些调试输出放在需要的析构函数中,并检查它是否实际被调用。

票数 3
EN

Stack Overflow用户

发布于 2014-03-16 22:38:15

Deconstructor什么也没做!(?)为什么?

因为在这种情况下它是空的。你以为它会做什么呢?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22442548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档