如何处理按值传递给委托的本机类型?

时间:2015-02-04 11:30:58

标签: c++-cli

通过值传递给委托调用的本机类会发生什么?

这是一个令我困惑的代码。我对Native的ctor / dtor调用的期望在代码中得到了注释。

输出:
土着ctor 3207236
原始副本ctor 3207240
M1
原生dtor 3207240
M2
原生dtor 3207240
M3
原生dtor 3207240
Native dtor 3207236

真实的结果对我来说很奇怪:
    每个委托处理程序调用Native的dtor,但Native的copy ctor只调用一次(在委托调用期间)。

这意味着按值传递给委托的对象创建一次(通过copy ctor),但是它的dtor被称为 3(!)次! 我不明白为什么。

有人可以解释一下为什么我的期望失败了吗?

class Native
{
public:
  Native()
  {
     Console::WriteLine("Native ctor {0}", __int64(this));
  }

  ~Native()
  {
     Console::WriteLine("Native dtor {0}", __int64(this));
  }

  Native(const Native& nat)
  {
     Console::WriteLine("Native copy ctor {0}", __int64(this));
  }
};

ref class Managed
{
public:
  delegate void Dele(Native);
  Dele^ m_delegate;

  Managed()
  {
     m_delegate = static_cast<Dele^>(Delegate::Combine(gcnew Dele(this, &Managed::m1), gcnew Dele(this, &Managed::m2), gcnew Dele(this, &Managed::m3)));
  }

  void m1(Native nat) // Expected: Native's copy ctor is called before Delegate calls the method 
                      // Reality: NO
  {
     Console::WriteLine("m1");
  } // Expected: Native's dtor is called; Reality: YES

  void m2(Native nat) // Expected: Native's copy ctor is called before Delegate calls the method
                    // Reality: NO
  {
     Console::WriteLine("m2");
  } // Expected: Native's dtor is called; Reality: YES

  void m3(Native nat) // Expected: Native's copy ctor is called before Delegate calls the method
                     // Reality: NO
  {
     Console::WriteLine("m3");
  } // Expected: Native's dtor is called; Reality: YES
};

int main(array<System::String ^> ^args)
{
   Native n; // Expected: Native's ctor is called; Reality: YES.
   Managed^ man = gcnew Managed();
   man->m_delegate(n); // Native's copy ctor is called; Reality: YES
   return 0;
} // Expected: Native's dtor is called; Reality: YES

0 个答案:

没有答案