Dynamic allocation of templates

Hi,

I'm having some problem with dynamic allocation of templates. My code contains a template class with a function that creates a new instance of the class, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
template <class T>

class determinant
{
	int m_n;
	T** m_values;
public:
	determinant(void);
	determinant(int n);
	~determinant(void);
	T Value(void);
	void SetValue(int x, int y, T value);
	void Print();
	determinant Minor(int x, int y);
	void SetSize(int size);
	T GetValue(int x, int y);
private:
	T min(T x, T y);
};

template <class T>
T determinant<T>::Value(void)
{
    using namespace std;
    cout<<"OK"<<endl;
	T result=0;

	if(m_n>1)
	{

		T* row1 = new T[m_n];
		determinant<T> *tempDets = new determinant<T>[m_n];

		for(int k=0;k<m_n;k++)
		{
			tempDets[k].SetSize(m_n-1);
		}

		for(int i=0;i<m_n;i++)
		{
			row1[i]=m_values[i][0];
			tempDets[i]=Minor(i,0);
		}

		for(int j=0;j<m_n;j++)
			result=result+tempDets[j].Value()*row1[j]*pow((double)-1,j);
	}

	else
	{
		return m_values[0][0];
	}

	return result;
}


The program runs into a segmentation fault at this line here:

determinant<T> *tempDets = new determinant<T>[m_n];

Is there a way to fix this or is template class recursion a really bad idea?
Did you initialize 'm_n'?
Yes, I've only included the class declaration and function definition otherwise there'd be lots more code. With hindsight I should probably have commented it as well.
Last edited on
And besides, if m_n wasn't initialised then T* row1 = new T[m_n]; would fail.
Interestingly, the program works fine in debugging mode.
Ok, after playing around I've discovered the error is due to declaring an array of the template class. So now it all boils down to, how do you declare an array objects from a class template?
Last edited on
As std::vector<T> or std::deque<T> or std::valarray<T>, where the vector is preferred for substitution of old-style ("C-Style") arrays by the standard.
But that doesn't solve the problem of why it's failing to construct an array of objects.
Let's see the constructor.
Also, the call stack would be useful in determining how deep in the recursion it went.

On a different note, replace pow((double)-1,j) with 1/j. 1.0/float(j), if you must, but don't call pow().
Topic archived. No new replies allowed.