Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

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

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 union I can "defer" calls to the constructor(s) and the destructor of the std::vector to the implementation of the unions constructor(s) / destructor.

// in foo.hh
struct Public {
  union Defer {
    std::vector<Hidden> v;
    Defer();
    // add copy/move constructor if needed
    ~Defer();
  } d;
};

Now I can use Public by only including foo.hh and linking with the file(s) implementing Public::Defer::Defer() and Public::Defer::~Defer(). Only those will need access to the full definition of Hidden.

Is this legal C++? If so, since when?

Background: Question that came up in my answer to another question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...