我创建了一个名为的指针类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
}
您的“复制构造函数”实际上不是复制构造函数:
//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
例如,它应该返回一些东西。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句