加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C – 我们为什么要在这个构造函数中使用explicit?

发布时间:2020-12-16 10:42:50 所属栏目:百科 来源:网络整理
导读:请参考 Wikipedia:Strategy Pattern (C++) class Context{ private: StrategyInterface * strategy_; public: explicit Context(StrategyInterface *strategy):strategy_(strategy) { } void set_strategy(StrategyInterface *strategy) { strategy_ = strat
请参考 Wikipedia:Strategy Pattern (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的构造函数中使用explicit是一个好习惯?

谢谢

解决方法

好吧,显式构造函数总是安全的,但可能不方便.如果您提供需要Context的StrategyInterface *,则explicit确保编译错误.这样做会阻止构建临时Context.这在某些情况下变得特别重要,例如:

> Context获取指向的StrategyInterface的所有权,并在析构函数中删除它
>上下文构建/销毁执行其他昂贵或不适当的操作
>它隐含地消除了一些操作的歧义,并使其他操作模糊不清,让程序员考虑如何解决歧义可能更合适(例如,如果尝试比较Context和StrategyInterface *会产生编译时错误,导致比较StrategyInterface * s,StrategyInterfaces或Contexts?)

如果Context实际上是一个StrategyInterface的替代品,只需要一些小的日志记录或其他增强,那么允许隐式构造可能是合适的,就像std :: string可以用const char *构造一样.当它们显然是独立的事物,或者当Context的生命周期超出任何给定的StrategyInterface使用时,则表明显式的构造函数.

(注意:这些指南非常粗略 – 更多的是起点而不是结束 – 欢迎评论)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读