C ++ - Why should we use explicit in this constructor?

Please refer to Wikipedia: strategy template (C ++)

class Context
{
    private:
        StrategyInterface * strategy_;

    public:
        explicit Context(StrategyInterface *strategy):strategy_(strategy)
        {
        }

        void set_strategy(StrategyInterface *strategy)
        {
            strategy_ = strategy;
        }

        void execute() const
        {
            strategy_->execute();
        }
};

Why is it recommended to use explicit for the context constructor?

thank

+3
source share
2 answers

Well, explicit constructors are always safe, but can be inconvenient. explicitprovides a compilation error if you specify StrategyInterface*where expected Context. In doing so, it prevents the creation of a temporary Context. This becomes especially important in certain circumstances, for example:

  • Contexttakes responsibility for the pointer to StrategyInterfaceand removes it in the destructor
  • Context / .
  • , , , (, a Context a StrategyInterface* , StrategyInterface* s, StrategyInterface Context s?)

a Context StrategyInterface, , , std::string const char*. Context a StrategyInterface, .

(: - , - )

+6

explicit, . Context , - , explicit.

+13

Source: https://habr.com/ru/post/1773568/


All Articles