C++偶遇系列:explicit

2017-05-31  本文已影响0人  再见小浣熊

explicit

explicit修饰符可以用于转化构造函数conversion constructor(C++98) 或者转化函数conversion function(C++11),禁止它们进行隐式转化implicit conversion或者拷贝初始化copy-initialization

:当构造函数只有一个非默认的参数(until C++11),并且没有用explicit修饰时,它就叫做转化构造函数conversion constructor

隐式转化存在的问题

当我们自定义了conversion,编译器会在合适的时机去进行隐式转化,一些情况下这些隐式转化是我们想要的,而另一些情况可能会违背程序的初衷。

最典型的就是Safe Bool Problem。如果没有用explicitA a; std::cout << 1 + a;等类似场景都是可以通过编译的;如果用了explicit,那场景中需要的类型必须是bool或者显示转化一下才能通过编译,if(b);或者std::cout << static_cast<bool>(b) + 1;

struct A
{
    A(int) { }      // converting constructor
    A(int, int) { } // converting constructor (C++11)
    operator bool() const { return true; }
};
 
struct B
{
    explicit B(int) { }
    explicit B(int, int) { }
    explicit operator bool() const { return true; }
};
 
int main()
{
    A a1 = 1;      // OK: copy-initialization selects A::A(int)
    A a2(2);       // OK: direct-initialization selects A::A(int)
    A a3 {4, 5};   // OK: direct-list-initialization selects A::A(int, int)
    A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
    A a5 = (A)1;   // OK: explicit cast performs static_cast
    if (a1) ;      // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization
 
//  B b1 = 1;      // error: copy-initialization does not consider B::B(int)
    B b2(2);       // OK: direct-initialization selects B::B(int)
    B b3 {4, 5};   // OK: direct-list-initialization selects B::B(int, int)
//  B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int)
    B b5 = (B)1;   // OK: explicit cast performs static_cast
    if (b2) ;      // OK: B::operator bool()
//  bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization
}

声明转化构造函数conversion constructor

声明转化函数conversion function

参考资料

上一篇 下一篇

猜你喜欢

热点阅读