Introduction
Looks like bug in Managed C++ when calling virtual member function with template argument.
Example
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
template <class T>
struct xroot
{
xroot() {}
xroot(T t) {}
xroot(const xroot &x) {}
~xroot() {}
};
class CClass
{
public:
virtual void func(xroot<int> x) {}
};
int _tmain(void)
{
CClass *c = new CClass();
c->func(5);
return 0;
}
Comment
By specification C++ the calls sequence in code
c->func(5);
should be next:
1. Call constructor xroot<int>(int t)
2. Call c->func with just constructed argument
3. Call destructor of argument
4. Return from c->func
But in Managed C++ project the sequence looks like:
1. Call constructor xroot<int>(int t)
2. Call destructor of just constructed xroot
3. Call c->func with just constructed argument
4. Call destructor of argument (again)
5. Return from c->func
but actually there no two destructor calls on one xroot - there is second xroot - constructed by default copy constructor. Yes, we have our copy constructor, but by compiler bug it isn't instanced. Instead compiler instanced default constructor. To check this uncomment fff() function - now the copy constructor will be instanced and calls sequence will be next:
1. Call constructor xroot<int>(int t)
2. Call copy constructor xroot<int>(const xroot<int> &x) with just constructed xroot
3. Call destructor of the first xroot
4. Call c->func with just constructed argument
5. Call destructor of the second xroot
6. Return from c->func
There are very interesting things - this issue exists only if:
1. In Management C++ project (Unmanaged C++ .NET works fine)
2. In template class/struct
3. Constructor of the template calls as argument of virtual member function
4. There are no any other code to push compiler to instance copy constructor
Conclusion
So, actually we have two bugs in Managed C++ compiler.
The first one - there is unnecessary to create second instance of argument by calling copy constructor - by specification the first one should be send to called function.
The second - compiler doesn't instancing copy constructor, but use default one.