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
};


谢谢

最佳答案

为什么我们必须定义这个朋友班


我很确定你不会;据我所知,没有任何东西引用另一个模板实例化的私有成员。如果复制构造函数或赋值运算符直接操作rhs.pointee而不是仅调用rhs.release(),则将需要它。


  我无法使用VS2010的上述代码编译此代码。


声明应为:

template<class U> friend class auto_ptr2;

10-07 15:49