1

在使用接口(无论如何都是概念)和抽象类并努力理解规则如何工作时,我试图了解五规则。

假设我有这样的布局:

#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该类需要为某些清理定义的析构函数,因此它们需要启动,但我不确定在哪里?在上面的示例中,我将它们放在接口类中,但我怀疑这是错误的,因为接口或抽象类中的任何复制/移动/析构函数都不需要定义或删除。

4

0 回答 0