I have encountered quite strange problem. Making long story short:
I have a code:
[EDIT:]
template <class DATA_TYPE,class INT_TYPE=std::size_t>
class Matrix
{
private:
INT_TYPE Rows, Cols;
DATA_TYPE *Data;
public:
Matrix(); //basic constructor
Matrix(const Matrix<DATA_TYPE,INT_TYPE> &M); //copy cnstructor
~Matrix(); //destructor
inline void Alloc(INT_TYPE _Rows,INT_TYPE _Cols);
inline void Free();
inline void Resize(INT_TYPE _Rows,INT_TYPE _Cols);
inline bool IsEmpty() const;
inline Matrix<DATA_TYPE,INT_TYPE>& operator =(const Matrix<DATA_TYPE,INT_TYPE>& M);
inline Matrix<DATA_TYPE,INT_TYPE>& operator ()(const Matrix<INT_TYPE,INT_TYPE> &M) const;
inline void Fill(DATA_TYPE Value=DATA_TYPE());
inline void Copy(const Matrix<DATA_TYPE,INT_TYPE> &M);
}; //CLASS DEFINITION END
template <class DATA_TYPE,class INT_TYPE>
inline Matrix<DATA_TYPE,INT_TYPE>::Matrix() //basic constructor
{
Rows=0;
Cols=0;
Data=NULL;
}
template <class DATA_TYPE,class INT_TYPE>
inline Matrix<DATA_TYPE,INT_TYPE>::Matrix(const Matrix<DATA_TYPE,INT_TYPE> &M) //copy constructor
{
Rows=0;
Cols=0;
Data=NULL;
Alloc(M.Rows,M.Cols);
std::copy(M.Data,M.Data+NumOfElements(),Data);
}
template <class DATA_TYPE,class INT_TYPE>
inline Matrix<DATA_TYPE,INT_TYPE>::~Matrix() //destructor
{
Free();
}
template <class DATA_TYPE,class INT_TYPE>
inline Matrix<DATA_TYPE,INT_TYPE>& Matrix<DATA_TYPE,INT_TYPE>::operator =(const Matrix<DATA_TYPE,INT_TYPE>& M) //Direct assignment operator
{
Copy(M);
return *this;
}
template <class DATA_TYPE,class INT_TYPE>
inline Matrix<DATA_TYPE,INT_TYPE>& Matrix<DATA_TYPE,INT_TYPE>::operator ()(const Matrix<INT_TYPE,INT_TYPE> &M) const
{
INT_TYPE N=M.NumOfElements();
Matrix<DATA_TYPE,INT_TYPE> Returned;
if (Rows==1) Returned.Resize(1,N);
else Returned.Resize(N,1);
{
INT_TYPE i;
for (i=0;i<N;i++) Returned.Data=Data[M.GetElement(i)];
}
return Returned;
}
When I use such a statement:
Matrix<float,int> m,a;
Matrix<int,int> ii;
m.Resize(5,5);
ii.Resize(3,1);
ii(0)=0;
ii(1)=1;
ii(2)=2;
a=m(ii); //crashes VS2010, and returns an bad_alloc exception on VS2008, Intel Compiler works fine with it
const Matrix<float,int> b=m(ii); //works fine
And trying to return the reference to some non const obect makes my PC suspend, VS2010 not responding and so on. Intel compiler or MSVC2008 runs with no problem at all. Is this normal for MSVC to behave this way? The problem is with reference. If operator () returns a copy everything works fine. But as I will use quite big objects I would like to avoid copying when necessary. But as far as I know if I use direct assignment operator with non const object (s2 here) it should automatically make a copy, but it suspends my PC.
In general, the code is taken without any change (except using template) from C++ for game programmers by MJ Dickheiser, so I assume that it should work.
Thanks & Regards :]