C++使用 shared_ptr 但调用了对象的关系运算符?

C++ using shared_ptr but having my object's relational operators called?

本文关键字:对象 关系 运算符 调用 shared 使用 ptr C++      更新时间:2023-10-16

我正在围绕写自己的堆班。我的模板堆类要求操作员'>'和'<'在模板类型上定义。

使用我写的示例类的实例(并且在int上也很好)时,所有这些都可以正常工作。但是,由于随着集体实例从堆中的不同节点移动,我决定看看当我创建班级共享_ptr的堆时发生了什么。虽然我确实看到构建的实例数量下降了,但堆似乎无法正常工作,因为它似乎是智能指针'>''and<'我想这只是比较智能指针参考。

就像许多STL类型一样,想到的一个解决方案允许进行比较类型,以便我可以将自己的比较类型传递到堆类中基础类型。

我在共享_ptr上阅读的一些文档说,他们实现了关系运营商(即<),以便可以将它们用作关联容器中的钥匙。我正在尝试考虑何时可能要使用shared_ptr作为密钥,而不是拥有自己的特定键。

我的样品类型的堆似乎正常:

heap<foo> foo_heap(heap_type::max);
for (unsigned int i = 0; i < 10; ++i)
    {
    std::string s = "string ";
    s += ('0' + i);
    foo f(i, s);
    foo_heap.push(f);
    }
cout << "root: " << foo_heap.top() << endl;

将我的示例类包装在不起作用的共享_ptr中,例如。堆的约束并不能按照我要完成的工作满足。

heap<shared_ptr<foo>> foo_heap_smart(heap_type::max);
for (unsigned int i = 0; i < 10; ++i)
    {
    std::string s = "string ";
    s += ('0' + i);
    shared_ptr<foo> f(new foo(i, s));
    foo_heap_smart.push(f);
    }
cout << "root: " << *(foo_heap_smart.top()) << endl;

我的样本foo类:

class foo
{
public:
    foo(int value, std::string s) : _value(value), _s(s)
    {
        std::cout << "foo::foo()" << std::endl;
    }
    foo(const foo& f) : _value(f._value), _s(f._s)
    {
        std::cout << "foo::foo(const foo& f)" << std::endl;
    }
    ~foo()
    {
        std::cout << "foo::~foo()" << std::endl;
    }
    virtual void operator=(const foo& f)
    {
        std::cout << "foo::operator=()" << std::endl;
        this->_value = f._value;
        this->_s = f._s;
    }
    virtual bool operator<(const foo& right)
    {
        return this->_value < right._value;
    }
    virtual bool operator>(const foo& right)
    {
        return this->_value > right._value;
    }
    void print(ostream& stm) const
    {
        stm << "value: " << this->_value << ", s: " << this->_s;
    }
private:
    int _value;
    std::string _s;
};

所以我认为许多人遇到了类似的问题。只是想知道规定的解决方案是什么。正如我提到的,我认为我知道看起来可能是一个很好的解决方案,但是想检查一下,因为智能指针可能会导致许多问题,因为它们实施了关系运营商。

谢谢尼克

如果默认操作员不适合您的需求,则规定的解决方案是提供您自己的比较操作员版本。对于您的heap类更好的设计也将是使用Comparator类型,该类型可以默认为std::less

template <typename T, typename Comp = std::less<T>>
class heap {
...
};

现在为您提供自己的less版本,专门用于shared_ptr

template <typename T>
struct less<shared_ptr<T>> {
    bool operator()(const shared_ptr<T>& a, const shared_ptr<T>& b) const {
      *a < *b;
    }
};

对于更好的设计,您可以添加一些元编程hack以使其仅适用于可以比较的T