无法将指针推回向量

时间:2017-08-08 09:31:02

标签: c++

我创建了一个名为p_pointer的指针类,并创建了一个用于保存p_pointer类型的向量。但是,当我尝试使用push_back函数时,它不起作用。我试图直接使用double*代替p_pointer (double),而push_back函数确实可以正常工作。所以我的猜测是我的拷贝构造函数有问题吗?

template<class T>
class p_pointer{
private:
    T* cp;
    size_t* refptr;

public:
    //default constructor
    p_pointer() : cp(0), refptr(new size_t(1)){}

    //copy constructor
    p_pointer (p_pointer&s) : cp(s.cp), refptr(s.refptr){
        *++refptr;
    }

    //assignment operator
    p_pointer& operator=(const p_pointer& s){
        ++*s.refptr;
        //freeing the left hand size if it is the last one
        if(--*refptr == 0){
            delete cp;
            delete refptr;
        }
        cp = s.cp;
        refptr = s.refptr;
    }

    //other assignment operator
    p_pointer& operator=(T* s){
        if(--*refptr == 0){
            delete cp;
            delete refptr;
        }
        cp = s;
        refptr = new size_t(1);
    }

};


int main()
{
    p_pointer<double> temp;
    temp = new double(1);

    std::vector<p_pointer<double> > collection;
    collection.push_back(temp); //error at here
}

1 个答案:

答案 0 :(得分:1)

你“复制构造函数”实际上不是复制构造函数:

//copy constructor
p_pointer (p_pointer&s):cp(s.cp),refptr(s.refptr){
*++refptr;
}

它应该接受const ref,而不是ref

有效的复制构造函数是:

//copy constructor
p_pointer (const p_pointer&s):cp(s.cp),refptr(s.refptr){
*++refptr;
}

中也存在编译错误
//other assignment operator
p_pointer&operator=(T* s){ 

它应该返回一些东西,例如*this