我写了一个智能指针类。当我将它传递给向量时,它会在编译时显示一些错误消息。但是在我删除显式声明后,它就起作用了。有什么错误?
explicit shared_ptr(const shared_ptr<T>& sp)
没有匹配的调用函数
shared_ptr<int>::shared_ptr(const shared_ptr<int> &)
#include <iostream>
#include <vector>
using namespace std;
template<class T>
class shared_ptr {
private:
struct ptr {
T* ptr;
size_t count;
void release() {
if(-- count == 0) {
delete ptr;
delete this;
}
}
};
private:
ptr* _ptr;
public:
explicit shared_ptr(T* p):
_ptr(new ptr) {
_ptr->ptr = p;
_ptr->count = 1;
}
explicit shared_ptr(const shared_ptr<T>& sp):
//explicit shared_ptr(const shared_ptr& sp):
_ptr(sp._ptr) {
++ _ptr->count;
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp) {
_ptr->release();
_ptr = sp._ptr;
++ _ptr->count;
return *this;
}
shared_ptr<T>& operator=(T* p) {
_ptr->release();
_ptr = new ptr;
_ptr->count = 1;
_ptr->ptr = p;
}
T* get() {
return _ptr->ptr;
}
T& operator*() {
return *(_ptr->ptr);
}
T* operator->() {
return _ptr->ptr;
}
~shared_ptr() {
_ptr->release();
}
};
int main() {
vector<shared_ptr<int> > vec;
vec.push_back(shared_ptr<int>(new int(10)));
}