c++ - 我应该在 C++11 中显式声明转换运算符吗?

标签 c++ c++11 type-conversion implicit-conversion

在C++11中,推荐:

  1. 显式定义我们自己的复制/移动构造函数,这样编译器就不会自己做(根据 [1] )。
  2. 将单参数构造函数显式声明为显式,以避免隐式转换(根据 [2] )。

按照这种思路,是否应该声明转换运算符 explicit 以防止编译器使用它们执行隐式转换?

最佳答案

In C++11,it is recommended:

  1. to explicitly define our own copy/move constructors, so that the compiler does not do it itself.

无论是谁提出这个建议,都是错误的。只要默认实现符合您的需要,就使用它。你自己可能不会让它变得更好。

  1. to explicitly declare one-argument constructors as explicit, to avoid implicit conversions.

C++ Core Guidelines说“默认情况下,声明单参数构造函数显式”。在某些情况下,您可能更愿意使用隐式构造(例如,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 函数调用更难阅读。写转换操作符,想隐式转换,想显式转换就写getter。

关于c++ - 我应该在 C++11 中显式声明转换运算符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34432464/

相关文章:

c++ - 临时对象中的成员变量是否尽可能隐式 move ?

c - 以下表达式中发生了什么转换?

c++ - 在 C++ 中对对象进行类型转换(请解释输出)

C++堆和ifstream读取函数

c++ - 混用 std: :'s and boost::' s::bind 和::function 会导致问题吗?

c++ - 如何实现线程向我的游戏添加计时器?

C++(有点)工厂

c++ - std::shared_ptr 在按引用传递时如何跨类层次结构转换?

c++ - 覆盖虚函数和隐藏非虚函数有什么区别?

c++ - 简单的c++输入函数