[英]Implementing Smart Pointer - storing template class in vector
我在将智能指针实例存储到容器时遇到麻烦。 这是指针的代码。
#include "std_lib_facilities.h"
template <class T>
class counted_ptr{
private:
T* pointer;
int* count;
public:
counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {} // default constructor
explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; } // copy constructor
~counted_ptr()
{
--*count;
if(!*count) {
delete pointer;
delete count;
}
}
counted_ptr& operator=(const counted_ptr& p) // copy assignment
{
pointer = p.pointer;
count = p.count;
++*count;
return *this;
}
T* operator->() const{ return pointer; }
T& operator*() const { return *pointer; }
int& operator[](int index) { return pointer[index]; }
int Get_count() const { return *count; } // public accessor for count
};
int main()
{
counted_ptr<double>one;
counted_ptr<double>two(one);
one = new double(5);
vector<counted_ptr<double> >test;
}
在int main()中, vector<counted_ptr<double> >
行会编译。 当我第一次使用vector<counted_ptr<double> >
尝试时,它没有编译(可能是因为它缺少参数。)但是,当我尝试使用诸如
test.push_back(one);
我收到一个打开vector.tcc的编译器错误,并显示特定错误:
no matching function for call to `counted_ptr<double>::counted_ptr(const counted_ptr<double>&)'|
我猜push_back找不到counted_ptr,但是我不确定。 任何帮助表示赞赏,谢谢。
编辑:但是,这有效。 test [0] = 1; 我想push_back的语义是限制它的原因。
您可能要尝试以下操作:
test.push_back(counted_ptr<double>(one));
您复制的构造函数是显式的,这意味着编译器不会隐式调用它。
就个人而言,我会将原始指针构造函数设为显式,而将副本ctor设为非明确。 那将更接近通常的行为。
编辑:我也建议您实现交换方法。 它使分配变得绝对琐碎。 您最终得到这样的结果:
counted_ptr &operator=(const counted_ptr &rhs) {
counted_ptr(rhs).swap(*this);
return *this;
}
这还具有在构造函数/析构函数中进行所有记帐的好处,这很容易管理:-)。
您的赋值运算符是错误的。
它指向的对象发生了什么?
如果您要分配给自己或相同的内部对象,会发生什么?
counted_ptr& operator=(const counted_ptr& p) // copy assignment
{
if (&p != this)
{
--*count;
if ((*count) == 0) // Much more readable than !*count
{
delete pointer;
delete count;
}
pointer = p.pointer;
count = p.count;
++*count;
}
return *this;
}
注意:编写自己的智能指针不是一个好主意。 它们不像您想象的那么琐碎。
注意:这是我发现的第一件事。 可能还有更多,我不确定这是100%正确的。
实际上,我会更改赋值运算符以使用复制/交换Idium。
counted_ptr& operator=(const counted_ptr& p) // copy assignment
{
counted_ptr<T> tmp(p); // increment counter on p
swap(tmp.pointer, pointer);
swap(tmp.count count);
return *this;
// tmp goes out of scope and thus the
// destructor gets called and what was in this
// object is now destroyed correctly.
}
// It may even be worth writing your own swap operator.
// Make sure you declare it as no-throw and grantee it.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.