tri*_*ker 1 c++ smart-pointers
我将智能指针的实例存储到容器中时遇到问题.这是指针的代码.
#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;
}
Run Code Online (Sandbox Code Playgroud)
在int main()中,该vector<counted_ptr<double> >行确实编译.当我第一次尝试它只是vector<counted_ptr<double> >它没有编译(可能是因为它缺乏参数.)但是,当我尝试使用push_back如
test.push_back(one);
Run Code Online (Sandbox Code Playgroud)
我收到一个编译错误,打开了vector.tcc,并指出了具体的错误
no matching function for call to `counted_ptr<double>::counted_ptr(const counted_ptr<double>&)'|
Run Code Online (Sandbox Code Playgroud)
我猜是push_back找不到count_ptr,但我真的不确定.任何帮助表示赞赏,谢谢.
编辑:但是,这有效.test [0] = 1; 我猜push_back的语义是限制它的.
你可能想试试这个:
test.push_back(counted_ptr<double>(one));
Run Code Online (Sandbox Code Playgroud)
复制构造函数是显式的,这意味着编译器不会隐式调用它.
就个人而言,我会使原始指针构造函数显式,并且复制ctor不显式.那将更接近通常的行为.
编辑:我还建议您实现交换方法.它使作业绝对无足轻重.你最终得到这样的东西:
counted_ptr &operator=(const counted_ptr &rhs) {
counted_ptr(rhs).swap(*this);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这也有利于构造函数/析构函数中发生的所有会计操作,管理起来要简单得多:-).