The behavior of value-initializing an enum

后端 未结 2 1298
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 14:55

First, I want to say, according to cppreference.com, it is somewhat impossible to value-initialize an enum.

According to http://en.cppreference.com/w/cpp/language/value_

2条回答
  •  孤独总比滥情好
    2021-02-01 15:06

    1: This can be undestood like so:

    enum class SomeEnum : int { V1 = 0, V2 = 1, V3 = 2 }; 
    SomeEnum a = 0; // compile error
    SomeEnum b = SomeEnum.V1; // OK
    

    This is basic protection from undefined behavior!

    2: Yes and Yes :)

    SomeEnum c = static_cast(1); // = SomeEnum.V2
    SomeEnum d = static_cast(5); // undefined behavior
    

    static_cast is dangerous by definition, it shoud only be used to support serrialization or old c interfaces!

提交回复
热议问题