我应该在 C++11 中显式声明转换运算符吗?
Should I declare conversion operators explicit in C++11?
在C++11中,推荐:
按照这个思路,是否应该声明转换运算符 explicit
以防止编译器使用它们执行隐式转换?
答案是"no, you should not"。显式转换运算符被添加到语言中以处理下面描述的特定问题。当您不处理该特定问题时,您应该向目标 class 添加一个显式复制构造函数,或者编写一个命名函数而不是转换运算符(如 c_str()
of std::string
).
让我们退一步考虑一般的转换。当您需要编写从 A
到 B
的转换代码时,您有两个选择 - 您可以定义一个单参数构造函数,例如
struct B {
B(const A& a);
};
或者您可以定义一个转换运算符,如下所示:
struct A {
operator B() const;
};
第一种方法允许在 C++11 之前使用 explicit/implicit 控件。但是,它在两种情况下不可用:
- 您拥有类型
A
但您不拥有类型 B
,或者
- 您拥有类型
A
,但类型 B
是 原始类型
根据 C++11 的显式转换运算符的 draft paper,委员会在争论是否要将显式转换运算符添加到语言中时,正是针对这两种情况。 (1) 隐式和隐式复制构造函数、(2) 隐式转换运算符和 (3) 命名成员函数已涵盖所有其他情况。
In C++11,it is recommended:
- to explicitly define our own copy/move constructors, so that the compiler does not do it itself.
无论是谁提出的建议,都是错误的。只要默认实现符合您的需要,就使用它。你自己可能不会让它变得更好。
- to explicitly declare one-argument constructors as explicit, to avoid implicit conversions.
C++ Core Guidelines 说“默认情况下,声明单参数构造函数 explicit
”。在某些情况下,您可能更愿意使用隐式构造(例如 std::string
来自 const char*
)。在这些情况下省略 explicit
声明。
Should one, in this train of thought, declare conversion operators explicit to prevent the compiler from using them to perform implicit conversions?
将它们明确化并没有什么好处。这意味着,转换只能与强制转换一起使用。转换比 getter 函数调用更难阅读。写转换运算符,要隐式转换的时候写getters,要显式转换的时候写
在C++11中,推荐:
按照这个思路,是否应该声明转换运算符 explicit
以防止编译器使用它们执行隐式转换?
答案是"no, you should not"。显式转换运算符被添加到语言中以处理下面描述的特定问题。当您不处理该特定问题时,您应该向目标 class 添加一个显式复制构造函数,或者编写一个命名函数而不是转换运算符(如 c_str()
of std::string
).
让我们退一步考虑一般的转换。当您需要编写从 A
到 B
的转换代码时,您有两个选择 - 您可以定义一个单参数构造函数,例如
struct B {
B(const A& a);
};
或者您可以定义一个转换运算符,如下所示:
struct A {
operator B() const;
};
第一种方法允许在 C++11 之前使用 explicit/implicit 控件。但是,它在两种情况下不可用:
- 您拥有类型
A
但您不拥有类型B
,或者 - 您拥有类型
A
,但类型B
是 原始类型
根据 C++11 的显式转换运算符的 draft paper,委员会在争论是否要将显式转换运算符添加到语言中时,正是针对这两种情况。 (1) 隐式和隐式复制构造函数、(2) 隐式转换运算符和 (3) 命名成员函数已涵盖所有其他情况。
In C++11,it is recommended:
- to explicitly define our own copy/move constructors, so that the compiler does not do it itself.
无论是谁提出的建议,都是错误的。只要默认实现符合您的需要,就使用它。你自己可能不会让它变得更好。
- to explicitly declare one-argument constructors as explicit, to avoid implicit conversions.
C++ Core Guidelines 说“默认情况下,声明单参数构造函数 explicit
”。在某些情况下,您可能更愿意使用隐式构造(例如 std::string
来自 const char*
)。在这些情况下省略 explicit
声明。
Should one, in this train of thought, declare conversion operators explicit to prevent the compiler from using them to perform implicit conversions?
将它们明确化并没有什么好处。这意味着,转换只能与强制转换一起使用。转换比 getter 函数调用更难阅读。写转换运算符,要隐式转换的时候写getters,要显式转换的时候写