Do unrestricted unions require placement new and a constructor definition?

前端 未结 2 940
借酒劲吻你
借酒劲吻你 2020-12-11 04:25

The examples I\'ve seen of unrestricted unions always seem to use placement new when constructing. The Wikipedia article for C++11 features uses placement new in the constru

2条回答
  •  离开以前
    2020-12-11 04:51

    No, placement new is not required here. The standard says that in case of unrestricted unions, the field constructors should be called explicitly, otherwise the fields will be uninitialized.

    You can call the constructor using traditional way

    U(): p() {}
    

    and exotic way

    U() { new(&p) Point(); }
    

    The second variant may be useful if it is not possible to construct the field before calling the constructor of U.

    Don't also forget about placement destructors in this case.

提交回复
热议问题