简体   繁体   中英

How come I can use a forward-declared class in a std::vector?

I thought that you could only create a reference or pointer member to a forward-declared class. However, I was surprised to discover this works:

#include <vector>

struct Donkey;

struct Cage
{
    std::vector<Donkey> donkeys;
};

struct Donkey
{
};

int main()
{
    Cage c;
}

http://ideone.com/EP0zKR

How come std::vector can be defined with a forward-declared class? Is this standard?

Actually, you can't.

Just because your program compiles (which is down to facts of the underlying implementation) does not mean it is valid.

There are times other than declaring a T* or a T& at which you may use a forward declaration ; it's just that this is not one of them .

It's undefined behavior.

[C++14/§17.6.4.8] 1 In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation.

[C++14/§17.6.4.8] 2 In particular, the effects are undefined in the following cases: [...]

  • if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

Furthermore, an incomplete type doesn't meet the allocator requirements:

[C++14/§17.6.3.5] 9 An allocator may constrain the types on which it can be instantiated and the arguments for which its construct member may be called. If a type cannot be used with a particular allocator, the allocator class or the call to construct may fail to instantiate.

Because your class has a definition by the time the vector is instantiated, it's fine. Be on the lookout for this proposal which will change allocator requirements, N4056 Minimal incomplete type support for standard containers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM