在C++中分配时,我们分配的对象是否会被破坏?

Ton*_*ark 4 c++ rule-of-three

以下代码片段是否泄漏?如果没有,那么在foobar()中构造的两个对象在哪里被破坏?

class B
{
   int* mpI;

public:
   B() { mpI = new int; }
   ~B() { delete mpI; }
};

void foobar()
{
   B b;

   b = B();  // causes construction
   b = B();  // causes construction
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ski 7

默认的复制赋值运算符执行成员方复制.

所以在你的情况下:

{
  B b;      // default construction.
  b = B();  // temporary is default-contructed, allocating again
            // copy-assignment copies b.mpI = temp.mpI
            // b's original pointer is lost, memory is leaked.
            // temporary is destroyed, calling dtor on temp, which also frees
            // b's pointer, since they both pointed to the same place.

  // b now has an invalid pointer.

  b = B();  // same process as above

  // at end of scope, b's dtor is called on a deleted pointer, chaos ensues.
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Effective C++,第2版中的第11项.