c++ - 实现智能指针 - 在 vector 中存储模板类

标签 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;
}

在 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 的语义是限制它的原因。

最佳答案

你可能想试试这个:

test.push_back(counted_ptr<double>(one));

您的复制构造函数是显式的,这意味着编译器不会隐式调用它。

就个人而言,我会将原始指针构造函数显式化,而复制构造函数则不显式化。这将更接近于通常的行为。

编辑:我还建议您实现交换方法。它使分配绝对微不足道。你最终得到这样的结果:

counted_ptr &operator=(const counted_ptr &rhs) {
    counted_ptr(rhs).swap(*this);
    return *this;
}

这也有利于在构造函数/析构函数中发生的所有会计,这更易于管理:-)。

关于c++ - 实现智能指针 - 在 vector 中存储模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1316601/

相关文章:

c++ - 在成员函数中声明指向不同类的指针

c++ - 标准流打印无关字符

c++ - 声明区域和范围有什么区别

c++ - 堆损坏

java - 传递给 C 的 JNI 回调

C++ 动态访问成员变量

c++ - shared_ptr 魔法 :)

c++ - 是否有推荐的方法来测试智能指针是否为空?

c++ - 如何初始化作为类成员的智能指针?

c++ - 为什么取消引用 unique_ptr 不会修改原始对象