templatized copy constructor not being deduced

L

lhr_cool_guy

The following code is compiling correctly on Visual Studio .NET 2003
but crashes. The problem is that the copy constructor is not being
called when it should be. Am I doing something wrong or is the compiler
at fault? I don't have any other compilers on which I could test this
:( If it IS a problem in the compiler, are there any workarounds?


template< class T >
class C
{
T * p;

public:

C();

template< class U >
C( const C< U > & ref );

~C();
};

template< class T >
C< T >::C< T >()
{
p = new double[3*4];
}

template< class T >
template< class U >
C< T >::C< T >( const C< U > & ref )
{
p = new double[3*4];
}

template< class T >
C< T >::~C< T >()
{
if ( p )
delete [] p;
}

template< class T >
C< T > inv( const C< T > & ref )
{
C< T > c;

return c;
}

int main()
{
C< double > c1, c2;

c2 = inv( c1 );

return 0;
}
 
Z

Zara

The following code is compiling correctly on Visual Studio .NET 2003
but crashes. The problem is that the copy constructor is not being
called when it should be. Am I doing something wrong or is the compiler
at fault? I don't have any other compilers on which I could test this
:( If it IS a problem in the compiler, are there any workarounds?

Some notes:

- if you provide one of: virtual destructor, copy constructor, copy
assignment, you should usually provide the others.

- copy constructor and copy assigment will never be instanced from
templated comnstructors/ assignment. You should write them explicitly,
or the compiler will generate them for you. BTW, that *is* your
problem, and double delete the crashing symptom.

Best regards,

-- Zara
 
N

Niklas Norrthon

Zara said:
Some notes:

- if you provide one of: virtual destructor, copy constructor, copy
assignment, you should usually provide the others.

Almost.

If you provide one of: (non trivial) destructor, copy constructor, or
copy assignment you should usually provide the others.

It doesn't matter if destructor is virtual or not. But often you
provide an empty virtual destructor just to make it possible to delete
objects by pointers to base class, and then it is not necessary to
provide copy constructor and copy assignment operators.
- copy constructor and copy assigment will never be instanced from
templated comnstructors/ assignment. You should write them explicitly,
or the compiler will generate them for you. BTW, that *is* your
problem, and double delete the crashing symptom.

Agree.

/Niklas Norrthon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top