C ++-为什么要在此构造函数中使用显式的? [英] C++ -- Why should we use explicit in this constructor?

查看:147
本文介绍了C ++-为什么要在此构造函数中使用显式的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考维基百科:策略模式(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();
        }
};

为什么将显式用于Context的构造函数是一种好习惯?

Why it is a good practice to use explicit for the constructor of Context?

谢谢

推荐答案

好,显式构造函数始终很安全,但可能会带来不便. explicit可确保您在期望提供Context的位置提供StrategyInterface*时出现编译错误.这样做可以防止构造临时Context.在某些情况下,这变得尤为重要,例如:

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获取指向的StrategyInterface的所有权,并在析构函数中将其删除
  • Context构造/破坏执行其他昂贵或不适当的动作
  • 它会隐式消除某些操作的歧义,而使其他操作变得模棱两可,这可能更适合让程序员考虑如何解决歧义(例如,应该尝试比较ContextStrategyInterface*产生编译-时间错误,导致比较StrategyInterface* s,StrategyInterface s或Context s?)
  • 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?)

如果Context实际上是StrategyInterface的替代品,只是有一些小的日志记录或其他增强功能,则允许隐式构造是适当的,因为std::string可以从const char*.当它们显然是独立的事物时,或者当Context的生存期应超过StrategyInterface的任何给定用法而存在时,则将指示显式构造函数.

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)

这篇关于C ++-为什么要在此构造函数中使用显式的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆