开发者

templated code not working while non-templated code works!

开发者 https://www.devze.com 2023-03-16 03:57 出处:网络
I spent several hours, completely stuck when I realized that only the templated version of my code has a bug.

I spent several hours, completely stuck when I realized that only the templated version of my code has a bug.

In the following code, when pushing_back elements in the myMap, the original vectors myVec1 and myVec2 are modified and contain garbage at the end of the execution. If I un-template everything, just replacing template<T> by double, then the code works fine as I would expect (the original arrays are untouched).

The funny thing is if I put a cout in the copy constructor, it does not get called if the code is templated. But it gets called if I replace the copy constructor with Vector<T2> by the original type Vector<T>, and then everything work fine.

Why wouldn't the compiler know that T2==T since I only use double?

(note, the code has been made as short as possible so as to show the errors - I thus removed accessors, made everything public etc.).

#include <vector>
#include <map>


template<class T>
class Vector{
public:
    Vector():n(0),data(0){};
    Vector(int N):n(N),data(new T[N]){};
    Vector(T x, T y):n(2),data(new T[2]){data[0]=x; data[1]=y;};
    template<class T2> Vector(const Vector<T2>& rhs):n(rhs.n), data(new T[n])
    {
        for (int i=0; i<n; i++)
            data[i] = T(rhs.data[i]);
    }   
    ~Vector(){delete[] data;}

    Vector& operator=(const Vector& rhs)
    {
        if (rhs.n != n)
        {
            if (data)
                delete[] data;
            data = new T[rhs.n];
        }
        n = rhs.n;
        memcpy(data, rhs.data, n*sizeof(T));
        return *this;
    }
    T& operator[](int i){return data[i];}
    const T& operator[](int i) const {return data[i];}
    int n;
    T* data;
};

typedef  Vector<double> Vectord;

template <class T> inline bool operator<(const Vector<T>& v1, const Vector<T>& v2)
{
    for (int i=0; i<v1.n; i++)
    {
        if (v1[i]<v2[i]) return true;
        if (v1[i]>v2[i]) return false;
    }
    return false;
}


int main(int argc, char** argv)
{
    std::vector<Vectord> myVec1(3);
    myVec1[0] = Vectord(1.,3.);
    myVec1[1] = Vectord(3.,3.);
    myVec1[2] = Vectord(1.,5.);

    std::vector<Vectord> myVec2(3);
    myVec2[0] = Vectord(4.,1.);
    myVec2[1] = Vectord(2.,5.);
    myVec2[2] = Vectord(6.,5.);

    std::map<Vectord, std::vector<Vectord> > myMap;
    for (int i=0; i<3; i++)
    {
        myMap[myVec开发者_高级运维1[i]].push_back(myVec2[i]);
    }



    return 0;
}


A templated constructor is never a copy constructor.

So your class is using the automatically generated copy constructor.

Cheers & hth.,

0

精彩评论

暂无评论...
验证码 换一张
取 消