why implicit conversion is harmful in C++

后端 未结 8 1641
臣服心动
臣服心动 2020-12-03 10:22

I understand that the keyword explicit can be used to prevent implicit conversion.

For example

Foo {

 public:
 explicit Foo(int i) {}
}
         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 10:36

    It introduces unexpected temporaries:

    struct Bar
    {
        Bar();      // default constructor
        Bar( int ); // value constructor with implicit conversion
    };
    
    void func( const Bar& );
    
    Bar b;
    b = 1; // expands to b.operator=( Bar( 1 ));
    func( 10 ); // expands to func( Bar( 10 ));
    

提交回复
热议问题