C++如何围绕智能指针生成多态包装类



你好,我正在为学校项目编写代码。在我目前的实现中,我在某些情况下使用多态性。例如,当我有一个集合或向量时:

std::vector<Parent *> vec;
vec.push_back(new Child1()); // adding instance of derived class
vec.push_back(new Child2()); // adding other instance of derived class

我可以使用此代码添加派生类的对象,但在使用集合的情况下,例如,我无法通过使用此方法防止重复,因为集合会将内存地址与另一个地址进行比较,而不是对象本身,所以我想使用包装器。另一方面,我的老师建议使用智能指针,如unique_ptrshared_ptr,以便正确清理内存。我发现第二种选择更容易使用。无论如何,即使我有:

std::set<std::shared_ptr<Parent>> s;
s.insert(std::make_shared<Child1>(Child1());
// ...
s.insert(std::make_shared<ChildN>(ChildN());

它仍然只适用于常规指针,并且允许重复。所以我想写一个包装类来防止这种情况发生,我有这样的东西:

template<typename T>
class PolymorphicWrapper {
private:
std::shared_ptr<T> ptr;
public:
PolymorphicWrapper(const std::shared_ptr<T> &ptr) : ptr(ptr) {}
const std::shared_ptr<T> &getPtr() const {
return ptr;
}
void setPtr(const std::shared_ptr<T> &ptr) {
PolymorphicWrapper::ptr = ptr;
}
bool operator==(const PolymorphicWrapper &rhs) const {
return *ptr == *rhs.ptr;
}
bool operator!=(const PolymorphicWrapper &rhs) const {
return rhs != *this;
}
bool operator<(const PolymorphicWrapper &rhs) const {
return *ptr < *rhs.ptr;
}
bool operator>(const PolymorphicWrapper &rhs) const {
return rhs < *this;
}
bool operator<=(const PolymorphicWrapper &rhs) const {
return rhs >= *this;
}
bool operator>=(const PolymorphicWrapper &rhs) const {
return *this >= rhs;
}
};

但是这种方法根本不适用于派生类!例如:

std::set<PolymorphicWrapper<Parent>> s;
s.insert(PolymorphicWrapper<Parent>(std::make_shared<ChildN>(ChildN()); // doesn't work

有简单的解决办法吗?我不太擅长编程,很难理解硬解决方案。但这是我必须通过的一项考试,才能继续学习其他科目。

std::set模板允许您指定密钥比较函数。与其扰乱指针类,只需为指针使用一个比较函数来比较它们所指向的内容

请参阅:https://en.cppreference.com/w/cpp/container/set

最新更新