Copying structs with uninitialized members

后端 未结 4 1770
迷失自我
迷失自我 2020-12-30 20:47

Is it valid to copy a struct some of whose members are not initialized?

I suspect it is undefined behavior, but if so, it makes leaving any uninitialized members in

4条回答
  •  灰色年华
    2020-12-30 21:06

    Yes, if the uninitialized member is not an unsigned narrow character type or std::byte, then copying a struct containing this indeterminate value with the implicitly defined copy constructor is technically undefined behavior, as it is for copying a variable with indeterminate value of the same type, because of [dcl.init]/12.

    This applies here, because the implicitly generated copy constructor is, except for unions, defined to copy each member individually as if by direct-initialization, see [class.copy.ctor]/4.

    This is also subject of the active CWG issue 2264.

    I suppose in practice you will not have any problem with that, though.

    If you want to be 100% sure, using std::memcpy always has well-defined behavior if the type is trivially copyable, even if members have indeterminate value.


    These issues aside, you should always initialize your class members properly with a specified value at construction anyway, assuming you don't require the class to have a trivial default constructor. You can do so easily using the default member initializer syntax to e.g. value-initialize the members:

    struct Data {
      int a{}, b{};
    };
    
    int main() {
      Data data;
      data.a = 5;
      Data data2 = data;
    }
    

提交回复
热议问题