Skip to content

Commit

Permalink
Add missing DVector<T>::operator=.
Browse files Browse the repository at this point in the history
DVector<T> was missing the assignment operator with RHS of another DVector<T>.
As a result, the default operator was being used, which resulted in an incorrect copying
of the pointers to the internally-allocated storage, and therefore a memory leak.
  • Loading branch information
tturocy committed Apr 16, 2024
1 parent 50d4067 commit 9b17656
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
22 changes: 20 additions & 2 deletions src/core/dvector.h
Expand Up @@ -36,14 +36,32 @@ template <class T> class DVector : public PVector<T> {
Array<int> dvlen, dvidx;

public:
explicit DVector(const PVector<int> &sig);
explicit DVector(const PVector<int> &shape);
DVector(const DVector<T> &v);
~DVector() override;

T &operator()(int a, int b, int c);
const T &operator()(int a, int b, int c) const;

DVector<T> &operator=(T c);
DVector<T> &operator=(const DVector<T> &v)
{
if (this == &v) {
return *this;
}
if (dvlen != v.dvlen || dvidx != v.dvidx) {
throw DimensionException();
}
static_cast<Vector<T> &>(*this) = static_cast<const Vector<T> &>(v);
return *this;
}

DVector<T> &operator=(const Vector<T> &v)
{
static_cast<Vector<T> &>(*this) = v;
return *this;
}

DVector<T> &operator=(const T &c);
};

} // end namespace Gambit
Expand Down
16 changes: 9 additions & 7 deletions src/core/dvector.imp
Expand Up @@ -31,7 +31,7 @@ namespace Gambit {
template <class T> void DVector<T>::setindex()
{
int index = 1;

for (int i = 1; i <= dvlen.Length(); i++) {
dvptr[i] = this->svptr + index - 1;
dvidx[i] = index;
Expand All @@ -43,15 +43,17 @@ template <class T> void DVector<T>::setindex()
// DVector<T>: Constructors, destructor, and constructive operators
//--------------------------------------------------------------------------

template <class T> DVector<T>::DVector(const PVector<int> &sig)
: PVector<T>((Array<int>)sig), dvlen(sig.Lengths().Length()),
dvidx(sig.Lengths().Length())
template <class T>
DVector<T>::DVector(const PVector<int> &shape)
: PVector<T>(static_cast<const Array<int> &>(shape)),
dvlen(shape.Lengths().Length()), dvidx(shape.Lengths().Length())
{
dvptr = new T **[dvlen.Length()];
dvptr -= 1;

for (int i = 1; i <= dvlen.Length(); i++)
dvlen[i] = sig.Lengths()[i];
for (int i = 1; i <= dvlen.Length(); i++) {
dvlen[i] = shape.Lengths()[i];
}

setindex();
}
Expand All @@ -70,7 +72,7 @@ template <class T> DVector<T>::~DVector()
if (dvptr) delete [] (dvptr + 1);
}

template <class T> DVector<T> &DVector<T>::operator=(T c)
template <class T> DVector<T> &DVector<T>::operator=(const T &c)
{
PVector<T>::operator=(c);
return *this;
Expand Down

0 comments on commit 9b17656

Please sign in to comment.