Is a vector with incomplete type allowed if absolutely no member functions are called? If so, since when?

后端 未结 1 1105
花落未央
花落未央 2020-12-19 16:09

Suppose I have some incomplete type

// in foo.hh
struct Hidden;

that I want to use as element type of a std::vector. Using an

相关标签:
1条回答
  • 2020-12-19 16:22

    Instantiating std::vector<T> with incomplete type T is undefined behavior up to C++14. In C++17 this limitation is relaxed somewhat:

    [vector.overview]/3 An incomplete type T may be used when instantiating vector if the allocator satisfies the allocator completeness requirements 17.6.3.5.1. T shall be complete before any member of the resulting specialization of vector is referenced.

    (Note: the default allocator std::allocator does satisfy those completeness requirements).

    My reading is that with C++17, it's legal for a translation unit to include your header (the one that forward-declares Hidden and defines Public), and define a variable Public pub; - but not to actually use any members of pub.d.v. Before C++17, merely including the header would already trigger undefined behavior.

    0 讨论(0)
提交回复
热议问题