q0987
q0987

Reputation: 35992

C++ -- why we have to define this friend template class

template<class T>
class auto_ptr2 {
public:
    explicit auto_ptr2(T *p = 0): pointee(p) {}
    template<class U>
    auto_ptr2(auto_ptr2<U>& rhs): pointee(rhs.release()) {}
    ~auto_ptr2() { delete pointee; }
    template<class U>
    auto_ptr2<T>& operator=(auto_ptr2<U>& rhs)
    {
        if (this != &rhs) reset(rhs.release());
        return *this;
    }
    T& operator*() const { return *pointee; }
    T* operator->() const { return pointee; }
    T* get() const { return pointee; }
    T* release()
    {
        T *oldPointee = pointee;
        pointee = 0;
        return oldPointee;
    }
    void reset(T *p = 0)
    {
        if (pointee != p) {
            delete pointee;
            pointee = p;
        }
    }
private:
    T *pointee;

    //template<class U> friend class auto_ptr2<U>;
        // Question 1> Why we have to define this friend class
        // Question 2> I cannot compile this code with above line with VS2010.
        // Error 1 error C3772: 'auto_ptr2<T>' : invalid friend template declaration
};

thank you

Upvotes: 0

Views: 1277

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254631

Why we have to define this friend class

I'm fairly sure you don't; as far as I can see, nothing is referencing the private member of a different template instantiation. You would need it if the copy constructor or assignment operator manipulated rhs.pointee directly, rather than just calling rhs.release().

I cannot compile this code with above line with VS2010.

The declaration should be:

template<class U> friend class auto_ptr2;

Upvotes: 3

Related Questions