提问人:incubus 提问时间:7/6/2021 最后编辑:François Andrieuxincubus 更新时间:7/6/2021 访问量:266
使用多态性时的五法则
Rule of five when using polymorphism
问:
在使用接口(无论如何是这个概念)和抽象类时,我试图弄清楚五法则,并努力理解规则是如何工作的。
假设我有一个这样的布局:
#include <memory>
#include <optional>
#include <string>
class IEventInterface {
protected:
IEventInterface() = default;
public:
virtual ~IEventInterface() = default;
/* rule of 5 says i need these too (https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-five) */
IEventInterface(const IEventInterface&) = delete; // copy constructor
IEventInterface& operator=(const IEventInterface&) = delete; // copy assignment
IEventInterface(IEventInterface&&) = delete; // move constructor
IEventInterface& operator=(IEventInterface&&) = delete; // move assignment
virtual std::optional<std::string> getEventText() noexcept = 0;
virtual bool isEnabled() noexcept = 0;
};
class AbstractEvent : public IEventInterface {
public:
AbstractEvent() : m_enabled { true } {}
virtual ~AbstractEvent() = default;
/* Do i need to disable the other copy/move operators here too? */
bool isEnabled() noexcept override {
return m_enabled;
}
private:
bool m_enabled;
};
class EventToday final : public AbstractEvent {
public:
EventToday() = default;
virtual ~EventToday() {
// some additional cleanup steps are required so no default here
}
std::optional<std::string> getEventText() noexcept override {
// some code here to get the event text....
}
std::unique_ptr<Collector> m_collector;
/* Do i need to disable the other copy/move operators here too? */
};
在其他一些代码中,我有一个充满 IEventInterface 的向量,例如std::vector<std::unique_ptr<IEventInterface>> m_events;
执行五条规则的正确位置在哪里?由于该类需要为某些清理定义析构函数,因此它们需要启动,但我不确定在哪里?
在上面的示例中,我将它们放在接口类中,但我怀疑这是错误的,因为接口或抽象类中的任何复制/移动/析构函数都不需要定义或删除。EventToday
答: 暂无答案
评论
IEventInterface
delete
EventToday
EventToday
default