在C++11中,推荐:
按照这种思路,是否应该声明转换运算符 explicit
以防止编译器使用它们执行隐式转换?
最佳答案
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说“默认情况下,声明单参数构造函数显式
”。在某些情况下,您可能更愿意使用隐式构造(例如,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/