我无法将智能指针的实例存储到容器中。这是指针的代码。
#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> >
它没有编译(可能是因为它缺少参数。)但是,当我尝试使用 push_back 时,例如
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,但我真的不确定。任何帮助表示赞赏,谢谢。
编辑:但是,这有效。测试[0] = 一;我猜 push_back 的语义是限制它的原因。