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

前端 未结 2 509
暖寄归人
暖寄归人 2021-01-21 07:22

Please refer to Wikipedia:Strategy Pattern (C++)

class Context
{
    private:
        StrategyInterface * strategy_;

    public:
        explicit Context(Strate         


        
相关标签:
2条回答
  • 2021-01-21 07:28

    Well, explicit constructors are always safe, but can be inconvenient. explicit ensures a compilation error should you provide a StrategyInterface* where a Context is expected. In doing so, it prevents construction of a temporary Context. This becomes particularly important in certain circumstances, e.g.:

    • Context takes ownership of the pointed-to StrategyInterface, and deletes it in the destructor
    • Context construction/destruction performs other expensive or inappropriate actions
    • it disambiguates some operations implicitly, and makes others ambiguous, where it might be more appropriate to have the programmer consider how to resolve the ambiguity (e.g. should an attempt to compare a Context and a StrategyInterface* produce a compile-time error, result in comparing StrategyInterface*s, StrategyInterfaces or Contexts?)

    If a Context is practically a drop-in-replacement for a StrategyInterface, just with some minor logging or other enhancements, then it may be appropriate to allow implicit construction, much as std::string can be constructed from const char*. When they're clearly independent things, or when the lifetime of a Context should exist beyond any given usage of a StrategyInterface, then an explicit constructor's indicated.

    (Note: these guidelines are pretty rough - more a starting point than an end - comments welcome)

    0 讨论(0)
  • 2021-01-21 07:28

    Because it's generally a good idea to use explicit unless you really want to allow implicit conversion. Since you're unlikely to use a Context object in a situation where you really gain anything from an implicit conversion, you're better off making it explicit.

    0 讨论(0)
提交回复
热议问题