3

オブジェクトがスタック上で破棄されるとどうなるかを理解しようとしています。ここに私のサンプルコードがあります:

#include <stdio.h>
struct B {
  ~B() {puts("BBBB");}
};

int main()
{
    B b;
    b.~B();
}

出力は

BBBB
BBBB

出力に基づいて、オブジェクトが 2 回破棄されていることがわかります。1 つは ~B() で、もう 1 つは "}" の後です。オブジェクトが2回破壊されるのはなぜですか?

更新:返信を確認した後、デストラクタはこのオブジェクトを破棄しないと思います。スコープ「}」の外に到達する前にオブジェクトを破棄する方法があります。ありがとう

4

8 に答える 8

2

手動でデストラクタを呼び出すのは、 placement newを使用する理由がある場合のみです。

于 2013-09-04T01:35:55.477 に答える
1

デストラクタは他の関数と同様であることに注意してください。他の関数との唯一の違いは、オブジェクトの割り当てが解除されたときに自動的に呼び出されることです。これはイベントのように見ることができます。オブジェクトが全滅する前に、すべてをきれいにするチャンスがあります。デストラクタを手動で呼び出しても、オブジェクトの割り当ては解除されません。

于 2013-09-03T19:52:44.320 に答える
0

あなたがやっていることは、変数が範囲を超えているというかなり良い例です。

int main()
{
  //Main is started

  B b;
  /* What happens is that `b` is constructed as a local 
     variable and put on the runtime stack.*/

  b.~B();
  /*You then invoke the destructor manually which is bad practice. 
    But it is possible and it will execute the code. 
    However, the state of the resulting instance is undefined.*/
}
/*Main ends and local variables defined in the 
  current scope get destroyed. Which also means that B's destructor 
  is called the second time */

参考までに、オブジェクトを手動で破棄する必要があるのは、次のようにヒープに置かれたときだけです。

// create an instance of B on the heap
B* b = new B();

// remove instance and implicitly call b's destructor.
delete b;
于 2013-09-03T19:52:41.897 に答える