Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Bug in managed c++

0.00/5 (No votes)
26 Aug 2004 1  
Looks like bug in managed c++ with unmanaget template class/struct

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) {}
};

/* 
void fff() {
    xroot<int> _a;
    xroot<int> _b(_a);
}
*/

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.

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here