C++使用 shared_ptr 但调用了对象的关系运算符?
C++ using shared_ptr but having my object's relational operators called?
我正在围绕写自己的堆班。我的模板堆类要求操作员'>'和'<'在模板类型上定义。
使用我写的示例类的实例(并且在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
。
相关文章:
- 对在不同二进制文件中创建的对象文件的依赖关系
- 运行线程和线程对象之间的关系
- 当我有两个对象时<<如何重载运算符?(有关系)
- 是否有一种有效的方法可以将一系列对象与父/子关系分类
- C++使用 shared_ptr 但调用了对象的关系运算符?
- C++ 如何重载关系运算符以检查两个对象是否相同
- 在C++中,当对象关系不直观时,如何重用代码?
- 通过包装器对象的构造函数将依赖关系传递给包装器对象
- 重载和对象定向之间的关系
- 操作之间的关系中的对象类型是什么?
- 现代C++对象关系
- C/C++Makefile:如何在with.C文件和其他目录中的对象文件之间建立依赖关系
- 缺少复制构造函数与对象切片有何关系
- 对象依赖关系和处理其中一个不再存在的情况
- 解决c++中对象之间的依赖关系
- 在c++中,当组合对象构造函数有依赖关系时,如何在初始化列表中强制它们的顺序
- c++共享对象依赖关系
- 在c++中,cin和cout对象与其类iostream的关系是怎样的?
- 用对象创建父/子关系
- c++对象之间的关系