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的替代品,只需要一些小的日志记录或其他增强,那么允许隐式构造可能是合适的,就像std :: string可以用const char *构造一样.当它们显然是独立的事物,或者当Context的生命周期超出任何给定的StrategyInterface使用时,则表明显式的构造函数. (注意:这些指南非常粗略 – 更多的是起点而不是结束 – 欢迎评论) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |