C ++-为什么要在此构造函数中使用显式的? [英] C++ -- Why should we use explicit in this constructor?
问题描述
请参考维基百科:策略模式(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
构造/破坏执行其他昂贵或不适当的动作 - 它会隐式消除某些操作的歧义,而使其他操作变得模棱两可,这可能更适合让程序员考虑如何解决歧义(例如,应该尝试比较
Context
和StrategyInterface*
产生编译-时间错误,导致比较StrategyInterface*
s,StrategyInterface
s或Context
s?)
Context
takes ownership of the pointed-toStrategyInterface
, and deletes it in the destructorContext
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 aStrategyInterface*
produce a compile-time error, result in comparingStrategyInterface*
s,StrategyInterface
s orContext
s?)
如果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屋!